python - 当我在 python 和 pyqt 中关闭应用程序时不运行类析构函数

标签 python multithreading pyqt

当我退出程序(sys.exit(app.exec_()))时,主窗体关闭,但有两个问题:
1 - MainForm 类的析构函数未运行
2 - 线程也在运行
我想当我关闭应用程序时,运行 MainForm 的析构函数并且所有线程也被杀死

    class MainForm(QMainWindow,Ui_MainWindow):
        def __init__(self,parent=None):
            super(MainForm,self).__init__(parent)
            self.setupUi(self)
            #...
        def init_main_form(self):
            #...
            self.show_time()
        def show_time(self):
            self.label_9.setText(u"{}:{}:{}".format(str(datetime.datetime.now().hour),str(datetime.datetime.now().minute),str(datetime.datetime.now().second)))
            self.label_9.resize(self.label_9.width()+len(self.label_9.text())*3,self.label_9.height())
            b = threading.Timer(1,self.show_time)
            #b.setName('localtime')
            #self.thread_list.append(b)
            b.start()
        def __del__(self):
            print("app is closed")
            for tr in threading.enumerate():
                if tr.isAlive():
                    tr._Thread__stop()
                    # or tr.finished
                    # or tr.terminate()
    def main():
        app = QApplication(sys.argv)
        main_form = MainForm()
        main_form.show()
        sys.exit(app.exec_())

    if __name__ == '__main__':
        main()

最佳答案

使用时请记住 per documentation __del__ 不能保证在解释器退出时运行。

__del__ 在 Python 的其他实现(如 Jython)中甚至更加棘手。您的应用程序不应依赖于它的执行才能正确运行。

关于python - 当我在 python 和 pyqt 中关闭应用程序时不运行类析构函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34121647/

相关文章:

python - 在 python 2.7 中并行运行函数以在其他函数末尾使用函数的输出

python - 从 Django 单元测试中获取通过或失败的输出

python - 如何在python中从url获取文件?

c# - 限制对资源的访问

python - python dict 和 PyQt 小部件之间连接的最佳方式是什么?

python - 关闭 QMainWindow 的正确方法

python - 窗口多维 Tensorflow 数据集

java - 提高java中的线程启动性能

python - 多处理中的有序状态打印

python - PyQt5 将小部件大小设置为最小并修复