pyqt4 qthread 崩溃 python

dme*_*ine 0 python multithreading pyqt anaconda

这是我通过复制各种教程和 SO 帖子创建的代码:

import sys

from PyQt4.QtGui import *
from PyQt4.QtCore import QObject, pyqtSignal, QThread

class Worker(QThread):
    def __init__(self):

        QThread.__init__(self)

class MainWindow(QWidget):

    def __init__(self):
        super().__init__()

        worker = Worker()
        worker.start()

if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = MainWindow()
    window.resize(640, 480)
    window.show()
    sys.exit(app.exec_())
Run Code Online (Sandbox Code Playgroud)

这很简单,但是当我运行它时,python 立即崩溃。我正在使用 Anaconda3,我非常确定 python 环境设置正确,但我可能是错的。我在 Windows 10、64 位、Anaconda3 和 Python 3.5(64 位)上。我使用 conda 安装了 qt4。

use*_*537 6

您的代码正在崩溃,因为工作线程在运行时被破坏。发生这种情况是因为它是在MainWindow. 之后__init__()完成和worker下降的范围之是受到Python的垃圾收集器中移除。为了避免这种情况发生,您可以将其分配workerMainwindow类的成员。

class MainWindow(QWidget):
    def __init__(self):
        super().__init__()
        self.worker = Worker()
        self.worker.start()
Run Code Online (Sandbox Code Playgroud)