Я пробовал этот пример из StackOverflow:
Как заставить дочерний поток закрыться, когда главное окно GUI закрыто в pyqt5 / python 3?
Я бы хотел, чтобы этот дочерний поток прерывался при закрытии основного приложения. В этом примере дочерний поток является простым счетчиком. Когда я закрываю основной 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_()
Я начал пытаться учить Python3 недель и go пожалуйста, будьте нежны Что я тут не так сделал?