Python 带有 PyQt5 多线程的 GUI

Python GUI with PyQt5 Multi Threading

我试图让我的应用程序支持与 GUI 相关的多线程,我试图从 GUI 外部的线程连接到 GUI 内部的方法,我从 那里得到了这个想法,它是标记为工作解决方案,我的错在哪里

下面是错误。

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()

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