如何使用 python 启动两个线程?

how to start two thread using python?

我有 3 个 python 个文件:

  1. 文件包括许多 class 使用 pyQt 初始化框架和其他 GUI 的任何方法。

  2. 包含从 Leap Motion 读取数据的 Leap Motion Listener class 的文件。

  3. 用于启动其他 classes.

  4. 的主文件

现在我想同时启动 GUI 框架和 Leap Motion class。我试图在主 class 中启动两个线程,但是有很多问题。

此代码仅对 运行 pyQt 框架有效:

import sys
from PyQt4 import QtCore, QtGui
from Painter import GUI_animate

class StartQT4(QtGui.QMainWindow):

    def __init__(self, parent=None):
        QtGui.QWidget.__init__(self, parent)
        self.ui = GUI_animate()
        self.ui.setupUi(self)

if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)
    myapp = StartQT4()
    myapp.show()
    sys.exit(app.exec_())

这就是我尝试对 运行 pyQt 框架和 Leap Motion class 做的事情 class :

import sys
from PyQt4 import QtCore, QtGui
from Painter import GUI_animate
import LeapMotion
from threading import Thread


class StartQT4(QtGui.QMainWindow):

    def __init__(self, parent=None):
        QtGui.QWidget.__init__(self, parent)

        t1 = Thread(target=show_frame())
        t2 = Thread(target=start_LeapMotion())
        t1.start()
        t2.start()
        self.ui.setupUi(self)

def start_LeapMotion():
    LeapMotion.main()

def show_frame():
    StartQT4.ui = GUI_animate()


if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)
    myapp = StartQT4()
    myapp.show()
    sys.exit(app.exec_())

但只有Leap Motion class 运行,从leap motion读完后,帧显示!

我怎样才能运行他们在一起?

当您将它们指定为线程的 target 时,请不要在 show_framestart_LeapMotion 之后放置成对的括号。 Python 将 functionName 解释为引用 <function functionName at (memory location)> 的变量,而 functionName() 是对该函数的调用。当您指定线程的 target 时,您确实 而不是 想要传递对该函数的调用;你想传递函数本身。如 API for the threading module 中所述,t1.start() 调用 Thread 对象的 run() 方法,除非您已覆盖它,否则 "invokes the callable object passed to the object's constructor as the target argument"--请注意 target 参数应该接收一个可调用对象(即函数本身,所以没有括号),而不是一个调用(这是你当前传递的)。