【问题标题】:Python GUI with PyQt5 Multi Threading带有 PyQt5 多线程的 Python GUI
【发布时间】:2018-02-27 10:03:50
【问题描述】:

我正在尝试使我的应用程序支持与 GUI 相关的多线程,我正在尝试从 GUI 外的线程连接到 GUI 内的方法,我从Simplest way for PyQT Threading 激发了这个想法,它被标记为工作解决方案,我的错在哪里

以下是错误。

class Communicate(QtCore.QObject):
    myGUI_signal = QtCore.pyqtSignal(str)

def myThread(callbackFunc):
# Setup the signal-slot mechanism.
    mySrc = Communicate()
    mySrc.myGUI_signal.connect(callbackFunc)

# Endless loop. You typically want the thread
# to run forever.
    while(True):
    # Do something useful here.
        msgForGui = 'This is a message to send to the GUI'
        mySrc.myGUI_signal.emit(msgForGui)


FORM_CLASS, _ = loadUiType(os.path.join(os.path.dirname('__file__'), "main.ui"))

class MainApp(QMainWindow, FORM_CLASS):  # QMainWindow refere to window type used in ui file
# this is constructor
    def __init__(self, parent=None):
        super(MainApp, self).__init__(parent)
        QMainWindow.__init__(self)
        self.setupUi(self)
        self.ui()
        self.actions()

    def ui(self):
        self.setFixedSize(848, 663)
    
    def actions(self):
        self.pushButton.clicked.connect(self.startTheThread)

    def theCallbackFunc(self, msg):
        print('the thread has sent this message to the GUI:')
        print(msg)
        print('---------')

    def startTheThread(self):
    # Create the new thread. The target function is 'myThread'. The
    # function we created in the beginning.
        t = threading.Thread(name = 'myThread', target = myThread, args =(self.theCallbackFunc))
        t.start()

def main():
    app = QApplication(sys.argv)
    window = MainApp()  # calling class of main window (first window)
    window.show()  # to show window
    app.exec_()  # infinit loop to make continous show for window

if __name__ == '__main__':
    main()

【问题讨论】:

  • 这和问题不完全相关,但是你在处理Qt的时候应该考虑使用QThread,它会避免你以后出现进一步的问题,比如GUI冻结...
  • 好的,我试试 QThread

标签: python python-3.x pyqt pyqt5 python-multithreading


【解决方案1】:

在实例化 Python 线程时,args 必须是元组或列表(或其他可迭代对象)。 args =(self.theCallbackFunc) 不是元组。 args =(self.theCallbackFunc,) 是一个元组(注意包含单个值的元组需要额外的逗号)。

【讨论】:

    猜你喜欢
    • 2017-10-30
    • 1970-01-01
    • 2017-12-08
    • 2021-03-31
    • 2017-11-20
    • 2020-04-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多