我们在进行GUI开发时会遇见假面假死情况,这样让用户体验非常差,为了防止这种情况的出现,那么我们要引进多线程概念
演示
- 首先创建一个带ui文件,我们命名为A.py
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'aa.ui'
#
# Created by: PyQt5 UI code generator 5.15.2
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again. Do not edit this file unless you know what you are doing.
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(261, 181)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.pushButton = QtWidgets.QPushButton(self.centralwidget)
self.pushButton.setGeometry(QtCore.QRect(80, 60, 75, 23))
self.pushButton.setObjectName("pushButton")
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 261, 23))
self.menubar.setObjectName("menubar")
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtWidgets.QStatusBar(MainWindow)
self.statusbar.setObjectName("statusbar")
MainWindow.setStatusBar(self.statusbar)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
self.pushButton.setText(_translate("MainWindow", "测试"))
2.创建main.py去调用A.py
from A import Ui_MainWindow
main.py完整代码
# -*- coding: utf-8 -*-
from PyQt5.QtCore import *
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow,QMessageBox
#调用UI
from A import Ui_MainWindow
qmut_1 = QMutex() # 创建线程锁
qmut_2 = QMutex()
# 继承QThread
class Thread_1(QThread, Ui_MainWindow): # 线程1
def __init__(self):
super().__init__()
def run(self):
qmut_1.lock() # 加锁
while True:
print('青柠分享:https://www.qingningz.cn/')
qmut_1.unlock() # 解锁
class MyMainWindow(QMainWindow, Ui_MainWindow):
def __init__(self, parent=None):
super(MyMainWindow, self).__init__(parent)
self.setupUi(self)
#pushButton为按钮
self.pushButton.clicked.connect(self.click_1) # 绑定槽函数
def click_1(self):
self.thread_1 = Thread_1() # 创建线程
self.thread_1.start() # 开始线程
if __name__ == "__main__":
app = QApplication(sys.argv)
myWin = MyMainWindow()
myWin.show()
sys.exit(app.exec_())
3.运行程序,点击按钮,代码就会调用main.py的Thread_1无限循环打印内容,界面也不会卡顿
© 版权声明
THE END
暂无评论内容