PyQt5 按钮运行功能和更新 LCD

2022-01-12 00:00:00 python python-3.x user-interface pyqt5

问题描述

我开始使用 Python 3 在 PyQt5 中创建 GUI.单击按钮时,我想运行randomint"函数并将返回的整数显示到名为lcd"的 QLCDNumber.

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 the QLCDNumber named "lcd".

这是我的代码:

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_())

我得到了输出:

TypeError:参数 1 具有意外类型NoneType"

TypeError: argument 1 has unexpected type 'NoneType'

如何让 LCD 显示函数randomint"的输出?

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


解决方案

问题是 button.clicked.connect 需要 slot(Python 可调用对象),但是 lcd.display 返回 .所以我们需要一个简单的 button.clicked.connect 函数(槽)来显示你新生成的值.这是工作版本:

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_())

相关文章