PyQt5 按钮运行功能和更新 LCD [英] PyQt5 button to run function and update LCD

查看:43
本文介绍了PyQt5 按钮运行功能和更新 LCD的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我开始使用 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_())

这篇关于PyQt5 按钮运行功能和更新 LCD的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆