python - 用 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_())
解决方案
他们在另一个答案中指出的是不正确的,在这种情况下 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)
推荐阅读
- excel - 对文本进行排名以查看他们是否有更好的健康计划
- wordpress - 如何在没有插件的情况下在管理页面中自定义 Wordpress 中的 404 页面?
- c# - 统一应用购买错误
- angular - 将服务中方法的返回值传递给另一个方法
- android - Content_mail.xml 文件未打开
- c# - powerbi api 总是返回 NotFound
- system-verilog - 如何使用 VPI 检查 Systemverilog 关联数组是否具有密钥
- python - 未找到字体
- bash - 在成功的“直到循环”之后,Bash 转换了我的 ping 命令
- python-3.x - 比较 2 个文件夹中的大型 csv 文件并打印精确的差异以及 python 中的行号