下面介绍如何实现PyQt5多线程运行的方法:
下面在第一个程序的基础上继续写:
(1)导入依赖库
import sys from demo import Ui_MainWindow from PyQt5.QtWidgets import QApplication, QMainWindow from PyQt5.QtCore import QThread
其中 Thread 是 PyQt5 的线程模块。
(2)线程函数
class new_thread(QThread): def __init__(self, Window): super(new_thread, self).__init__() self.window = Window def run(self): self.window.label.setText('hello')
包括两个部分:类的初始化(init)以及线程函数(run),在初始化类的时候需要将界面(Window)传进来,才能在线程中对界面进行操作。
(3)主函数
class Window(QMainWindow,Ui_MainWindow): def __init__(self, parent=None): super(Window,self).__init__(parent) self.setupUi(self) self.new_thread = new_thread(self) self.pushButton.clicked.connect(self.new_thread.start)
这里启动线程用的是(start)而不是(run)函数.
(4)运行
if __name__ == "__main__": app = QApplication(sys.argv) win = Window() win.show() sys.exit(app.exec_())