简体   繁体   English

如何在PyQt5中更新QLabel?

[英]How do I update a QLabel in PyQt5?

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

I am attempting to create a dice rolling simulator using PyQt5 with Python 3.5 on a 32 bit Windows 7 Machine. 我正在尝试在32位Windows 7计算机上使用带有Python 3.5的PyQt5创建骰子滚动模拟器。 The problem I am having is that I am not able to Update the QLabel/QPixmap to display a different random dice image when the 'Roll' button is clicked. 我遇到的问题是,单击“滚动”按钮后,我无法更新QLabel / QPixmap以显示其他随机骰子图像。 When the 'Roll' button is clicked I get a 'Python has stopped working' error message and the program closes. 单击“滚动”按钮时,出现“ Python停止工作”错误消息,程序关闭。 I've been trying to solve the problem for a while and according to everything I have read my current code should work, but it does not. 我一直在尝试解决问题一段时间,根据我阅读的所有内容,我当前的代码应该可以工作,但事实并非如此。

you need to create reference to self, 您需要创建对自我的参考,

self.dice = QLabel(self)
...
def rolldice(self):
        new_dice = QPixmap('dice ' + str(random.randint(1,6)) + '.png').scaled(160, 300, Qt.KeepAspectRatio, Qt.FastTransformation)
        self.dice.setPixmap(new_dice)
        QApplication.processEvents()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM