2017-04-21 18 views
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マシンでPython 3.5でPyQt5を使用してサイコロローリングシミュレータを作成しようとしています。私が抱えている問題は、QLabel/QPixmapを更新して、「ロール」ボタンをクリックしたときに異なるランダムなサイコロ画像を表示できないことです。 'ロール'ボタンをクリックすると、「Pythonが動作を停止しました」というエラーメッセージが表示され、プログラムが終了します。私はしばらくの間、問題を解決しようとしていましたが、私が現在読んでいるすべてのコードがうまくいくはずですが、そうではありません。あなたは、自己への参照を作成する必要が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() 
+0

は、それが動作するようになりました、ありがとうございました。あなたは自己への参照を作成しなければならない理由を説明できますか? –

関連する問題