首页 > 解决方案 > 无法在主线程启动的线程上运行 python GUI。任何替代方案或解决方法?

问题描述

我一直在为一个多线程项目尝试 python GUI 框架,该项目需要 GUI 完全在从主线程开始的线程上运行,并引用在不同线程上更新的变量。但是,当我在主线程以外的线程上运行 GUI 时,它会立即关闭并且我得到

“QApplication::exec:必须从主线程调用”

当使用 pyqt5 和

“RuntimeError:主线程不在主循环中”

使用 tkinter 时。

我想知道是否有人知道另一个 python GUI 框架可以让我在主线程以外的线程上运行它,或者是否有办法解决这个错误。

这是使用 pyqt5 复制第一条消息的示例

import  threading, sys

from PyQt5.QtCore import QObject
from PyQt5.QtWidgets import QMainWindow, QApplication


class Example(QMainWindow):

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

        self.app=app
        self.initUI()


    def initUI(self):
        self.setGeometry(300, 300, 290, 150)
        self.setWindowTitle('Example')
        self.show()

    def principal(self):

        sys.exit(self.app.exec_())


def main():

    app = QApplication(sys.argv)
    example = Example(app)

    #sys.exit(example.app.exec_())

    exampleThread = threading.Thread(target=example.principal, name='example')
    exampleThread.start()

main()

标签: pythonmultithreadinguser-interfacetkinterpyqt5

解决方案


推荐阅读