【问题标题】:How do I update a QLabel in PyQt5?如何在 PyQt5 中更新 QLabel?
【发布时间】:2017-04-21 19:01:43
【问题描述】:
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 已停止工作”错误消息并且程序关闭。我一直在尝试解决这个问题一段时间,根据我阅读的所有内容,我当前的代码应该可以工作,但它没有。

【问题讨论】:

    标签: python python-3.x pyqt pyqt5 qlabel


    【解决方案1】:

    你需要创建对自我的引用,

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

    【讨论】:

    • 非常感谢,现在可以使用了。你能解释一下为什么你必须创建对自我的引用吗?
    猜你喜欢
    • 2019-04-23
    • 1970-01-01
    • 2016-09-10
    • 1970-01-01
    • 2021-08-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多