Loading

pyqt5 多线程+定时器+读取本地图片

前言

一个程序界面有多个button 按钮时,单击一个按钮,若此按钮对应的信号正在执行,且还未执行完毕;
此时再次单击另外一个按钮,就会出现假死状态。

这个时候我们就需要使用 多线程去解决

多线程+定时器+读取本地图片

# coding:utf-8
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from UU2 import *
import sys
import time

a = 0


class Thread_1(QThread):  # 线程1
    def __init__(self):
        super().__init__()

    def run(self):
        values = [1, 2, 3, 4, 5]
        while True:
            for i in values:
                print(i)
                time.sleep(0.5)  # 休眠


class Thread_2(QThread):  # 线程2
    def __init__(self):
        super().__init__()

    def run(self):
        values = ["a", "b", "c", "d", "e"]
        for i in values:
            print(i)
            time.sleep(0.5)


class MainWindous(QtWidgets.QMainWindow, Ui_MainWindow):
    def __init__(self):
        super(MainWindous, self).__init__()
        self.thread_2 = Thread_2()  # 创建线程
        self.thread_1 = Thread_1()  # 创建线程
        self.setupUi(self)
        self.timer = QTimer()  # 初始化一个定时器
        self.pushButton.clicked.connect(self.startTimer)  # 开始按钮 对应槽
        self.pushButton_2.clicked.connect(self.endTimer)  # 关闭按钮 对应槽
        self.pushButton_3.clicked.connect(self.pic)  # 开启图片按钮 对应槽
        self.pushButton_4.clicked.connect(self.pic_close)  # 停止图片按钮 对应槽

    def startTimer(self):
        # self.timer.start(1000)              # 开始定时,参数为定时时间间隔
        # print("start")
        self.thread_1.start()  # 开始线程
        global a
        a = 1
        print("start")

    def endTimer(self):
        print("end")
        self.thread_2.start()  # 开始线程
        global a
        a = 0

    def pic(self):
        if a == 1:
            self.timer.timeout.connect(self.pic1)  # 每次计时到时间时发出信号
            self.timer.start(3000)  # 设置计时间隔并启动;单位毫秒
        else:
            QtWidgets.QMessageBox.critical(self, "错误", "请先开始程序")

    def pic1(self):
        if a == 1:
            self.label.setText("加载照片")
            print("图片加载成功")
            # self.thread_3.start()  # 开始线程
            # 加载本地图片
            img_path = "./1.jpg"
            self.label_2.setPixmap(QPixmap(img_path))
            self.label_3.setPixmap(QPixmap("./1.jpg").scaled(200, 200))  # 显示图片尺寸
            QtWidgets.QApplication.processEvents()
        else:
            print("错误")
            self.timer.stop()

    def pic_close(self):
        self.timer.stop()


if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    mainWindow = MainWindous()
    mainWindow.show()
    sys.exit(app.exec_())

成果图

posted @ 2021-01-06 15:58  Unixcs  阅读(1194)  评论(0编辑  收藏  举报