python - 在 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,所以请保持温和。我在这里做错了什么?
解决方案
推荐阅读
- javascript - 轮播内容出现然后消失
- openoffice.org - 如何在 Open Office writer 中全选
- spring-boot - 在 Spring Boot 中正常关闭时连接池关闭错误
- r - openNLPdata中的R错误中的实体识别
- python - 如何解决“重新索引仅对唯一值索引对象有效”错误
- javascript - 主题之间的 jQuery 过渡(切换主题时)
- css - Css 未使用 express/handlebars 加载到页面上
- kubernetes - 无法重用现有的持久卷 (GlusterFS)
- c++ - 在 C++ 中允许使用 memset
- r - 在ggplot2中使用geom_sf时使用annotation_raster放置图像