PyQt5 button to run function and update LCD

前端 未结 2 1315
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-06 15:08

I am getting started with creating GUI\'s in PyQt5 with Python 3. At the click of the button I want to run the \"randomint\" function and display the returned integer to th

相关标签:
2条回答
  • 2020-12-06 15:21

    The problem is that the button.clicked.connect expects the slot (Python callable object), but lcd.display returns None. So we need a simple function (slot) for button.clicked.connect which will display your newly generated value. This is 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_())
    
    0 讨论(0)
  • 2020-12-06 15:30

    Another way of resolving the TypeError: argument 1 has unexpected type 'NoneType is to prefix your slot with lambda: like so:

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

    I actually don't know why but it's a solution that worked for me.

    0 讨论(0)
提交回复
热议问题