【问题标题】:How to use Threading in Python pyqt4 GUI design [duplicate]如何在 Python pyqt4 GUI 设计中使用线程
【发布时间】:2018-08-25 20:26:42
【问题描述】:

我编写了一个简单的 python GUI 代码,用于让我的代码休眠 10 秒。同时,图形用户界面应该在不冻结的情况下运行。不能通过定义主线程和辅助线程来实现吗?当我单击“运行”按钮时,pythonw.exe 已停止工作。有人对我如何解决这个问题有任何想法吗?谢谢你。

    import sys, threading
    from PyQt4 import QtGui, QtCore
    from PyQt4.QtCore import pyqtSlot
    from PyQt4.QtGui import *

    class Window(QtGui.QMainWindow):
        def __init__(self):
            super(Window,self).__init__()
            self.setGeometry(400,150, 550, 500)
            self.setWindowTitle("my first program")
            self.home()

        def home(self):
            self.button_1 = QtGui.QPushButton('Run', self)
            self.button_1.resize(60,25)
            self.button_1.move(230,230)
            self.button_1.clicked.connect(self.Thread_test)

            self.textbox_1 = QTextEdit(self)
            self.textbox_1.move(15,290)
            self.textbox_1.resize(510,170)

            self.show()

        def Thread_test(self):
            t = threading.Thread(target=self.calculation)
            t.start()

        def calculation(self):
            msg="program is working"
            self.textbox_1.setText(msg)
            time.sleep(5)
            msg="program was slept for few sec."
            self.textbox_1.setText(msg)

    def run():
        app=QtGui.QApplication(sys.argv)
        GUI=Window()
        sys.exit(app.exec_())    
    run()

【问题讨论】:

    标签: python multithreading pyqt4


    【解决方案1】:

    Qt 小部件不是线程安全的。您应该只从创建它的线程访问一个小部件。见http://doc.qt.io/qt-5/thread-basics.html:

    所有小部件和几个相关类 [...] 都不能在辅助线程中工作。

    您必须通知您的主 (GUI) 线程来更新 UI。您可以使用信号和插槽来做到这一点。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-03-03
      • 2015-10-27
      • 2012-12-02
      • 1970-01-01
      • 2013-01-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多