0
import random
import sys
from PyQt5.QtCore import (Qt)
from PyQt5.QtWidgets import (QHBoxLayout, QToolTip, QPushButton, QApplication, QWidget, QLabel)
from PyQt5.QtGui import (QIcon, QPixmap, QFont)
class dicesimulator(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
QToolTip.setFont(QFont('SansSerif', 10))
dice = QLabel(self)
smaller_pixmap = QPixmap('dice ' + str(random.randint(1,6)) +'.png').scaled(160, 300, Qt.KeepAspectRatio, Qt.FastTransformation)
dice.setPixmap(smaller_pixmap)
dice.move(1, 1)
btn = QPushButton('Roll', self)
btn.setFont(QFont('SansSerif', 20))
btn.setToolTip('Click to Roll Die')
btn.clicked.connect(self.rolldice)
btn.resize(162, 40)
btn.move(0, 161)
self.setGeometry(1427, 30, 162, 201)
self.setFixedSize(self.size())
self.setWindowTitle('Dice Simulator')
self.setWindowIcon(QIcon('icon.png'))
self.show()
def rolldice(self):
new_dice = QPixmap('dice ' + str(random.randint(1,6)) + '.png').scaled(160, 300, Qt.KeepAspectRatio, Qt.FastTransformation)
dice.setPixmap(new_dice)
QApplication.processEvents()
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = dicesimulator()
ex.show()
sys.exit(app.exec_())
我正在嘗試在32位Windows 7機器上使用PyQt5和Python 3.5創建一個骰子滾動模擬器。我遇到的問題是我無法在單擊「滾動」按鈕時更新QLabel/QPixmap以顯示不同的隨機骰子圖像。當「滾動」按鈕被點擊時,我得到一個'Python已停止工作'的錯誤信息,程序關閉。我一直在試圖解決這個問題一段時間,根據我讀過的所有內容,我當前的代碼應該可以工作,但事實並非如此。如何更新PyQt5中的QLabel?
非常感謝你,現在它工作。你能解釋爲什麼你必須創建自我的參考。 –