PyQt5:多线程

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_())
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

我是一个对称矩阵

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值