問題描述
我開始使用 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的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!