我有 3 个 python 文件:
文件包含许多使用 pyQt 初始化 Frame 和其他 GUI 的类方法。
包含从 Leap Motion 读取数据的 Leap Motion Listener 类的文件。
用于启动其他类的主文件。
现在我想一起启动 GUI 框架和 Leap Motion 类。我尝试在主类中启动两个线程,但有很多问题。
此代码仅适用于运行 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 类的方法:
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类运行,读完Leap Motion后,帧显示!
我怎样才能将它们一起运行?
最佳答案
不要将成对的括号放在show_frame
之后和start_LeapMotion
当您将它们指定为 target
时线程的。 Python解释functionName
作为引用 <function functionName at (memory location)>
的变量,而functionName()
是对该函数的调用。当您指定线程的target
时,您不想想要传递对该函数的调用;你想传递函数本身。正如 API for the threading module 中所述, t1.start()
调用Thread
对象的run()
方法,除非您重写它,否则“调用作为 target 参数传递给对象构造函数的可调用对象” - 请注意 target
参数应该接收一个可调用对象(即函数本身,因此没有括号),而不是一个调用(这就是您当前传递的内容)。
关于python - 如何使用python启动两个线程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30274323/