PyQt5 button to run function and refresh LCD

I start by building a GUI in PyQt5 using Python 3. On the click of a button, I want to run the "randomint" function and display the returned integer in a QLCDNumber named "lcd".

Here's my code:

import sys
from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QPushButton, QLCDNumber
from random import randint


class Window(QWidget):
    def __init__(self):
        super().__init__()
        self.initui()

    def initui(self):
        lcd = QLCDNumber(self)

        button = QPushButton('Generate', self)
        button.resize(button.sizeHint())

        layout = QVBoxLayout()
        layout.addWidget(lcd)
        layout.addWidget(button)

        self.setLayout(layout)
        button.clicked.connect(lcd.display(self.randomint()))

        self.setGeometry(300, 500, 250, 150)
        self.setWindowTitle('Rand Integer')
        self.show()

    def randomint(self):
        random = randint(2, 99)
        return random

if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = Window()
    sys.exit(app.exec_())

      

I am getting output:

TypeError: argument 1 has unexpected type "NoneType"

How can I get the LCD to display the output of the "randomint" function?

+3


source to share


2 answers


The problem is what is button.clicked.connect

expecting a slot (a Python callable object) but lcd.display

returning None

. Therefore, we need a simple function (slot) for button.clicked.connect

that will display your newly created value. This is a working version:



import sys
from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QPushButton, QLCDNumber
from random import randint


class Window(QWidget):
    def __init__(self):
        super().__init__()
        self.initui()


    def initui(self):
        self.lcd = QLCDNumber(self)

        button = QPushButton('Generate', self)
        button.resize(button.sizeHint())

        layout = QVBoxLayout()
        layout.addWidget(self.lcd)
        layout.addWidget(button)

        self.setLayout(layout)
        button.clicked.connect(self.handleButton)

        self.setGeometry(300, 500, 250, 150)
        self.setWindowTitle('Rand Integer')
        self.show()


    def handleButton(self):
        self.lcd.display(self.randomint())


    def randomint(self):
        random = randint(2, 99)
        return random


if __name__ == '__main__':

    app = QApplication(sys.argv)
    ex = Window()
    sys.exit(app.exec_())

      

+2


source


Another way to resolve TypeError: argument 1 has unexpected type 'NoneType

is to prefix your slot with the lambda:

following:

self.tableWidget.cellChanged['int','int'].connect(lambda:self.somefunction())

      



I really don't know why, but this is the solution that worked for me.

0


source







All Articles