首页 > 解决方案 > 用 Python PyQT5 掷骰子

问题描述

如何使用随机数设置图像我的意思是如果出现 1 则将加载 1dot 图像。请给我一个解决方案。它会生成数字并加载图像,但我不知道如何为每次按下滚动时创建逻辑它会根据随机数 1 到 6 更改图像。

import random
import sys
from PyQt5.QtGui import QPixmap
from PyQt5.QtWidgets import (QApplication,QMainWindow, QPushButton,QTextEdit,QLabel,QFileDialog)
class MainWindow(QMainWindow):
    def __init__(self):
        QMainWindow.__init__(self)
        self.setFixedSize(400,400)
        self.setWindowTitle("Simple Dice roller")
        
        self.button = QPushButton('Roll', self) #button connection
        self.button.clicked.connect(self.clickmethod) #methodclicked button  connection
        self.button.clicked.connect(self.imageview) # buttonimageview connection
        self.msg =  QTextEdit(self) #for showing text while clicking on button in box
        
        self.msg.resize(100,32)
        self.msg.move(100,100)
        
        self.button.resize(100,32)
        self.button.move(50,50)
        self.imageview()
       
    def clickmethod(self):
        ran = str(random.randint(1,6))
        self.msg.setText(ran)

    def imageview(self):
        label = QLabel(self)
        label.move(100, 110)
        label.setFixedSize(500, 300)
        pixmap = QPixmap(r'S:\Dice sumilator\diceimage\1dot.jpg')
        #pixmap = QPixmap(r'S:\Dice sumilator\diceimage\2dots.jpg')
        label.setPixmap(pixmap)
                        
if __name__ == "__main__":    
    app = QApplication(sys.argv)
    Diceroll = MainWindow()
    Diceroll.show()
    sys.exit(app.exec_()) 

标签: pythonpyqtpyqt5

解决方案


他们在另一个答案中指出的是不正确的,在这种情况下 QGraphicsPixmapItem 和 QLabel 具有相同的容量,因为它们都用于显示 QPixmap。在何时遇到困难或其他被错误记录的事情时,这里没有区别。

如果要随机选择图像,则必须创建图像列表并使用 random.choices 随机获取图像并更新 QLabel 显示的 QPixmap:

class MainWindow(QMainWindow):
    def __init__(self):
        QMainWindow.__init__(self)
        self.setFixedSize(400, 400)
        self.setWindowTitle("Simple Dice roller")

        self.button = QPushButton("Roll", self)
        self.button.clicked.connect(self.clickmethod)
        self.msg = QTextEdit(self)

        self.msg.resize(100, 32)
        self.msg.move(100, 100)

        self.button.resize(100, 32)
        self.button.move(50, 50)
        self.label = QLabel(self)
        self.label.move(100, 110)
        self.label.setFixedSize(500, 300)

    def clickmethod(self):
        images = [
            r"S:\Dice sumilator\diceimage\1dot.jpg",
            r"S:\Dice sumilator\diceimage\2dots.jpg",
        ]
        random_image = random.choices(images)
        pixmap = QPixmap(random_image)
        self.label.setPixmap(pixmap)

推荐阅读