首页 > 解决方案 > PyQt5 窗口在终止线程时冻结

问题描述

在 pyqt5 中,当我尝试为我的程序关闭踏板时,Ui 冻结并停止响应。我是 pyqt5 的新手,无法找到答案。

这些是主窗口(GUI)文件中的方法

def clickButton_on(self):
    print("clicked on/off")
    ControlPanel.start()

def clickButton_Off(self):
    print("clicked on/off")
    ControlPanel.stop()

这是 controlPanel 类的方法

@classmethod
def start(cls):
    print('start method fired')
    cls.th = threading.Thread(target=cls.test,args=(cls.attr,))
    cls.th.start()

@classmethod
def stop(cls):
    print('stop method fired')
    cls.th.join()

重新创建问题的完整代码

from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.uic import loadUi 
import sys
import threading

class MainWindow(QtWidgets.QMainWindow):

    def __init__(self):

        super(MainWindow,self).__init__()

        self.b1 = QtWidgets.QPushButton(self)
        self.b1.setText("on")

        self.b2 = QtWidgets.QPushButton(self)
        self.b2.setText("off")
        self.b2.move(50,50)

        self.b1.clicked.connect(self.clickButton_on)
        self.b2.clicked.connect(self.clickButton_Off)


    def clickButton_on(self):
        print("clicked on/off")
        ControlPanel.start()

    def clickButton_Off(self):
        print("clicked on/off")
        ControlPanel.stop()

class ControlPanel:

    n=2

    @classmethod
    def start(cls):
        print('start method fired')
        cls.th = threading.Thread(target=cls.test,args=(cls.n,))
        cls.th.start()

    @classmethod
    def stop(cls):
        print('stop method fired')
        cls.th.join()

    @classmethod
    def test(cls,n):
        print('test method fired')
        n= 0 
        while True:
            n += 0.1
            print(f'thread running n = {n}')

if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    window = MainWindow()
    window.show()
    app.exec_()

窗户完全冻结。它不会使用 .join() 关闭线程,它线程会继续运行。

标签: python-3.xmultithreadinguser-interfacepyqt5

解决方案


推荐阅读