前言
一個程序界面有多個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_())