首页 > 解决方案 > 在 pyqt5 / pythonx3 中关闭主 GUI 窗口时,子线程不会关闭

问题描述

我从 StackOverflow 尝试了这个例子:

在pyqt5 / python 3中关闭主GUI窗口时如何关闭子线程?

我希望这个子线程在我关闭主应用程序时终止。在这个例子中,子线程是一个简单的计数器。当我关闭主 GUI 时,计数器仍在继续。当 GUI 窗口关闭时,如何让线程结束?

我的代码在这里:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Apr 11 12:41:26 2020

@author: Pietro
"""

from PyQt5 import QtWidgets
from PyQt5.QtWidgets import (QWidget, QApplication,QPushButton, 
                             QVBoxLayout)
from PyQt5.QtCore import QThread
import time, threading, sys





class testScriptApp(QtWidgets.QWidget):

    def __init__(self, parent=None):
        # initialize the widget
        QtWidgets.QWidget.__init__(self, parent)
        # set the window title
        self.setWindowTitle("Scripting")
        # manage the layout
        self.center()
        self.resize(400,400)
        self.mainGrid = QVBoxLayout()
        self.button = QPushButton('Start')
        self.button.clicked.connect(self.on_click)
        self.mainGrid.addWidget(self.button)
        self.setLayout(self.mainGrid)



    def center(self):
        qr = self.frameGeometry()
        cp = QtWidgets.QDesktopWidget().availableGeometry().center()
        qr.moveCenter(cp)
        self.move(qr.topLeft())

    def on_click(self):
        global running
        print('global running : ' , running)
        self.worker = Worker()
        self.worker.run()

    def closeEvent(self, event):
        global running
        running = False
        print('Closing')
#       self.worker.terminate()
        event.accept()

class Worker(QThread):

    def __init__(self):
        QThread.__init__(self)

    def run(self):
        count=1
        global running
        while count>0 and not running:
#        while count>0:
            print('counter on: ',count, running)
            time.sleep(2)
            count+=1
        else:
            print('out of loop')
            return

if __name__ == "__main__":
    running = False
    app = QtWidgets.QApplication(sys.argv)
    myapp = testScriptApp()
    myapp.show()
    app.exec_()

我在 3 周前开始尝试学习 Python,所以请保持温和。我在这里做错了什么?

标签: pythonpython-3.xmultithreadingpyqt5

解决方案


推荐阅读