我已经编写了一个简单的python GUI代码,用于将我的代码休眠10秒钟。同时,GUI应该不冻结地运行。通过定义主线程和辅助线程是不可能的吗?当我单击“运行”按钮时,pythonw.exe已停止工作。有人对我如何解决此问题有任何想法吗?谢谢。
import sys, threading
from PyQt4 import QtGui, QtCore
from PyQt4.QtCore import pyqtSlot
from PyQt4.QtGui import *
class Window(QtGui.QMainWindow):
def __init__(self):
super(Window,self).__init__()
self.setGeometry(400,150, 550, 500)
self.setWindowTitle("my first program")
self.home()
def home(self):
self.button_1 = QtGui.QPushButton('Run', self)
self.button_1.resize(60,25)
self.button_1.move(230,230)
self.button_1.clicked.connect(self.Thread_test)
self.textbox_1 = QTextEdit(self)
self.textbox_1.move(15,290)
self.textbox_1.resize(510,170)
self.show()
def Thread_test(self):
t = threading.Thread(target=self.calculation)
t.start()
def calculation(self):
msg="program is working"
self.textbox_1.setText(msg)
time.sleep(5)
msg="program was slept for few sec."
self.textbox_1.setText(msg)
def run():
app=QtGui.QApplication(sys.argv)
GUI=Window()
sys.exit(app.exec_())
run()
答案 0 :(得分:0)
Qt窗口小部件不是线程安全的。您应该仅从创建窗口小部件的线程访问窗口小部件。参见http://doc.qt.io/qt-5/thread-basics.html:
所有小部件和几个相关的类在辅助线程中均不起作用。
您将必须通知您的主(GUI)线程来更新UI。您可以使用信号和插槽来实现。