pyqt5 点击开始按钮,执行事件,中途点击暂停按钮后,所执行的事件暂停
要想实现上述情况,我们需要用到线程。将我们要执行的时间变为线程而不是进程。
效果:
做了如下一个界面:
生成的python文件为TextView,代码为:
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'TextView.ui'
#
# Created by: PyQt5 UI code generator 5.11.3
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_Form(object):
def setupUi(self, Form):
Form.setObjectName("Form")
Form.resize(338, 170)
self.pushButton = QtWidgets.QPushButton(Form)
self.pushButton.setGeometry(QtCore.QRect(60, 70, 93, 28))
self.pushButton.setObjectName("pushButton")
self.pushButton_2 = QtWidgets.QPushButton(Form)
self.pushButton_2.setGeometry(QtCore.QRect(180, 70, 93, 28))
self.pushButton_2.setObjectName("pushButton_2")
self.retranslateUi(Form)
QtCore.QMetaObject.connectSlotsByName(Form)
def retranslateUi(self, Form):
_translate = QtCore.QCoreApplication.translate
Form.setWindowTitle(_translate("Form", "Form"))
self.pushButton.setText(_translate("Form", "开始"))
self.pushButton_2.setText(_translate("Form", "暂停"))
有定义一个文件为textV,代码为:
from PyQt5 import QtWidgets
from TextView import Ui_Form
import threading
class MainV(QtWidgets.QWidget, Ui_Form):
def __init__(self):
super().__init__()
self.setupUi(self)
self.action()
self.flag = 0
def action(self):
self.pushButton.clicked.connect(self.a)
self.pushButton_2.clicked.connect(self.off)
def a(self):
t = threading.Thread(target=self.on, name='t')
t.start()
def on(self):
self.flag = 1
print("线程开启")
while True:
if self.flag == 1:
print('11111')
else:
break
print("暂停成功!")
def off(self):
self.flag = 0
print('22222')
if __name__ == '__main__':
import sys
app = QtWidgets.QApplication(sys.argv)
mainV = MainV()
mainV.show()
sys.exit(app.exec_())
其中下面的函数中采用线程是关键点:
def a(self):
t = threading.Thread(target=self.on, name='t')
t.start()
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/84733.html