欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

pyqt5 点击开始按钮,执行事件,中途点击暂停按钮后,所执行的事件暂停

程序员文章站 2024-02-16 09:31:04
...

pyqt5 点击开始按钮,执行事件,中途点击暂停按钮后,所执行的事件暂停

要想实现上述情况,我们需要用到线程。将我们要执行的时间变为线程而不是进程。
效果:

pyqt5 点击开始按钮,执行事件,中途点击暂停按钮后,所执行的事件暂停
做了如下一个界面:
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()
相关标签: thread