【多线程】python界面阻塞,白屏,not responding解决的简单例子

 # -*- coding: utf-8 -*-

 import sys, time
from PyQt4.QtCore import *
from PyQt4.QtGui import *
x = 0
class Window(QWidget):
def __init__(self, parent = None):
QWidget.__init__(self, parent)
self.thread = Worker() # 提示信息
self.xLable = QLabel("Number of xTimes:")
# 下拉框
self.spinBox = QSpinBox()
self.spinBox.setMaximum(100)
self.spinBox.setValue(10)
self.startButton = QPushButton(self.tr("&Start"))
# 布局
layout = QGridLayout()
layout.addWidget(self.xLable, 0, 0)
layout.addWidget(self.spinBox, 0, 1)
layout.addWidget(self.startButton, 0, 2)
self.setLayout(layout)
# 标题
self.setWindowTitle(self.tr("Threading")) # 信号
self.connect(self.thread, SIGNAL("finished()"), self.finishSend)
self.connect(self.thread, SIGNAL("update(int)"), self.updateGUIStatus)
self.connect(self.startButton, SIGNAL("clicked()"), self.sendAdvMail) def sendAdvMail(self):
self.spinBox.setReadOnly(True)
self.startButton.setEnabled(False)
#传递值到线程中
self.thread.render(self.spinBox.value()) def updateGUIStatus(self, leftTime):
self.xLable.setText(str(leftTime)) def finishSend(self):
self.spinBox.setReadOnly(False)
self.startButton.setEnabled(True) class Worker(QThread):
def __init__(self, parent = None):
QThread.__init__(self, parent)
self.exiting = False
self.xTimes = 0 def __del__(self):
self.exiting = True
self.wait() def render(self, xTimes):
self.xTimes = xTimes
self.start() def run(self):
# Note: This is never called directly. It is called by Qt once the
# thread environment has been set up.
n = self.xTimes
while not self.exiting and n > 0:
time.sleep(1)
#该信号引起界面更新
n -= 1
self.emit(SIGNAL("update(int)"), n) if __name__ == "__main__":
app = QApplication(sys.argv)
window = Window()
window.show()
sys.exit(app.exec_())

编辑器加载中...

上一篇:问题-Delphi在多线程中使用其他窗体上的控件,报“尚未调用CoInitialize”解决方法


下一篇:习题3.5 求链表的倒数第m个元素(20 分)浙大版《数据结构(第2版)》题目集