1、介绍
pyqt5中只有MainWindow是主线程,如果你想在其中循环干点啥,那么在此期间整个界面都无法移动,因为此时程序被卡在循环中,无法对你的移动命令做出反应,那么如何实现循环又不影响主界面主线程呢?
2、threading
threading是python中的用于多线程的库。
现在我们想实现点击按钮”开启新线程“后,下方按钮会自动从1变到100,并且在此期间还能拖动界面
程序如下,让按钮去触发一个函数,该函数会定义新线程(指定了要运行的函数)并启动,则要运行的函数就在新线程中运行起来了
import sys
import time
from PyQt5.QtWidgets import *
import threading
class MainWindow(QMainWindow):
def __init__(self):
super(MainWindow, self).__init__()
self.setWindowTitle("测试")
self.resize(600, 400)
self.button=QPushButton(self)
self.button.setText("开启新线程")
self.button.clicked.connect(self.buttoned) # 让buttoned开新线程去循环改变button2的文本
# self.button.clicked.connect(self.newThread) # 直接调用newThread()函数,那么主界面就会卡在循环里
self.button_2 = QPushButton(self)
self.button_2.move(50,50)
self.button_2.setText('0')
def buttoned(self):
thr=threading.Thread(target=self.newThread) # 定义一个线程,target定义要运行的函数
thr.start() # 开始线程
def newThread(self):
for i in range(100):
self.button_2.setText(str(i))
time.sleep(1)
app = QApplication([])
demo = MainWindow()
demo.show()
sys.exit(app.exec_())