Python PyQt4线程,共享变量

Python PyQt4 Threading, sharing variables

这几天我一直在研究这个话题,没有找到适合我申请的答案。我正在使用 PyQt4 在 python 2.7 中构建一个 GUI 来与机器人交互。我需要一个线程(main)到 运行 使用 QT Designer 创建的 GUI 和另一个线程(worker)来不断地向机器人传输数据和从机器人传输数据。我想在无限工作线程中使用在 GUI(主线程)中输入的数据。在我看过的所有教程中,数据仅从 worker 发送到主线程;就像通常的 "loading bar" 示例一样。

这就是我目前所拥有的。该程序从 QT Designer 导入 GUI 输出,并在按下时将值打印到控制台。我还设置了一个无限线程,它可以将 "hello" 打印到确实有效的控制台。只是为了让我指出正确的方向,你能告诉我如何在单击名为 "pushbutton" 的按钮时将无限打印 "hello" 更改为其他内容吗?我熟悉 C/C++,但这是我的第一个 Python 项目,如有任何帮助,我们将不胜感激。

from PyQt4 import QtGui, QtTest, QtCore # Import the PyQt4 module we'll need
import sys # We need sys so that we can pass argv to QApplication

import gui # Import the GUI output from QT Designer


class GUI(QtGui.QMainWindow, gui.Ui_MainWindow):  # This class is to interact         with the GUI
def __init__(self):
    super(self.__class__, self).__init__()
    self.setupUi(self)  
    self.threadclass = ThreadClass()
    self.threadclass.start() # start thread class

    #########  Binds GUI widgets with functions  #####
    self.connectbutton.clicked.connect(self.pushbutton) # Call function "pushbutton" when pressed
    self.motor_up.clicked.connect(self.motorup) # Call function motorup when pressed
    self.motor_down.clicked.connect(self.motordown) # Call function motorup when pressed
    self.motor_speed_slider.valueChanged.connect(self.slider) # Call function slider
    self.auto_manual_check.stateChanged.connect(self.checkbox) # Call function checkbox
    self.Kp_box.valueChanged.connect(self.kp_entry)
    self.Ki_box.valueChanged.connect(self.ki_entry)
    self.Kd_box.valueChanged.connect(self.kd_entry)


    ######### Functions to run when GUI event is encountered

def pushbutton(self): # stuff to do if connect button is pressed                ## THIS BUTTON
    self.connectlabel.setText("Connected")
    QtTest.QTest.qWait(2000)        
    self.connectlabel.setText("Disconnected")
    self.emit(SIGNAL("text(Qstring)"),"it worked")

def slider(self): # Stuff to do when slider is changed
    print(self.motor_speed_slider.value()) # Print to monitor

def motorup(self): # Run if motor up is clicked
    print("motor up")

def motordown(self): # Run if motor down is clicked
    print("motor down")

def checkbox(self): # Run if checkbox is changed
    if self.auto_manual_check.isChecked():
        print("is checked")
    else:
        print("unchecked")

def kp_entry(self): # Run if kp is changed
    print(self.Kp_box.value())

def ki_entry(self): # Run if ki is changed
    print(self.Ki_box.value())

def kd_entry(self):# Run if kd is changed
    print(self.Kd_box.value())



class ThreadClass(QtCore.QThread): # Infinite thread to communicate with  robot
def __init__(self, parent = None):
    super(ThreadClass, self).__init__(parent)

def run(self):
    while 1:            # Runs continuously 
        print "hello"   #                           CHANGE THIS WHEN pushbutton IS PRESSED




def main():  # Function to run the main GUI
app = QtGui.QApplication(sys.argv)  # A new instance of QApplication
form = GUI()                 # We set the form to be our ExampleApp 
form.show()                         # Show the form
app.exec_()                         # and execute the app


if __name__ == '__main__':              # if we're running file directly and not importing it
main()                              # run the main function

编辑: 感谢您快速而详细的回复。在尝试了您的解决方案之后,我想我越来越接近了,但是我没有让它们为我的应用程序工作,我想我最初的问题可能还不清楚。我本质上是在尝试在线程之间传递变量,实际打印只是为了表明变量已成功传输。我认为这个精简的代码会清除它。

from PyQt4 import QtGui, QtTest, QtCore # Import the PyQt4 module we'll need
import sys # We need sys so that we can pass argv to QApplication

import gui # Import the GUI output from QT Designer


class GUI(QtGui.QMainWindow, gui.Ui_MainWindow):            # This class is to interact with the GUI
def __init__(self):
    super(self.__class__, self).__init__()
    self.setupUi(self)  
    self.threadclass = ThreadClass()
    self.threadclass.start() 
    self.Kp_box.valueChanged.connect(self.kp_entry)     # Call function kp_entry if box value is changed

def kp_entry(self):                                     # Run if kp is changed                  
    print(self.Kp_box.value())                          # I WANT TO SEND THE BOX VALUE TO THE WORKER THREAD        

class ThreadClass(QtCore.QThread):                          # Infinite thread to communicate with robot
def __init__(self, parent = None):
    super(ThreadClass, self).__init__(parent)

def run(self):
    while 1:             
        print self.Kp_box.value()                       #CONTINUOUSLY PRINT THE UPDATED BOX VALUE    


def main():                             # Run the main GUI
   app = QtGui.QApplication(sys.argv)  # A new instance of QApplication
   form = GUI()                        # We set the form to be our ExampleApp 
   form.show()                         # Show the form
   app.exec_()                         # and execute the app

if __name__ == '__main__':              # if we're running file directly and not importing it
main()                              # run the main function

我想要做的就是使用户能够更新 GUI 中的值,然后将该值传递给工作线程。在这种情况下,我有一个输入框,因此用户可以更改号码。然后我需要程序将该数字传输到将与机器人通信的工作线程。现在代码不起作用,我只是尽可能接近它以更好地展示我正在尝试做的事情。

如果有帮助,这是我的 GUIhere

有几种方法可以做到这一点。第一个(最简单的)是在你的方法中加入一行代码 pushbutton:

def pushbutton(self):
    self.threadclass.got_a_click()

在ThreadClass中添加一个对应的方法和实例变量,并更改运行方法:

def __init__(self):
   super(ThreadClass, self).__init__(parent)
   self.flag = False

def got_a_click(self):
    self.flag = True

def run(self):
    while not self.flag:
        print "hello"
    do_something_useful()

这可能已经足够好了。注意方法got_a_click 运行s在主循环上下文中,run方法在辅助QThread上下文中。

一种更复杂的方法是使用 Qt 的能力将信号发送到其他线程中的插槽。为此,您必须 运行 辅助线程中的 QEventLoop。 QThread 基础 class 已经为此设置:它有一个 run 方法,只包含一个事件循环。因此,为了让 QThread subclass 成为 运行 事件循环,只需不要覆盖 运行 方法即可。这个 QThread 将只是坐在那里什么也不做,直到一个信号被发送到它的一个插槽。当发生这种情况时,插槽将在辅助线程中执行。代码如下所示:

class ThreadClass(QtCore.QThread): 
    def __init__(self, parent = None):
        super(ThreadClass, self).__init__(parent)
        self.moveToThread(self)

    def onButtonPress(self):
        pass  # Your code here

将此行添加到 GUI 的构造函数中: self.connectbutton.clicked.connect(self.threadclass.onButtonPress)

每次单击按钮时,onButtonPress 运行 次线程上下文中。

注意 ThreadClass 构造函数中的语句 self.moveToThread(self)。这个非常重要。它告诉QtSignal/Slot机制,这个对象中的所有Slot都要通过ThreadClass线程中的事件循环来调用。没有它,Slot onButtonPress 将在主线程的上下文中 运行,即使它的代码位于 ThreadClass.

另一个需要注意的陷阱是直接调用 onButtonPress。那会 不使用 Signal/Slot 机制,onButtonPress 将像任何普通的 Python 函数一样执行。例如,如果您从现有函数 pushbutton 调用 onButtonPress,它将在主线程上下文中调用 运行。为了获得您想要的线程行为,您必须将 Qt 信号发射到 onButtonPress 插槽。

这是您重新表述的问题的答案。以下代码片段按您的预期工作:

from PySide import QtGui, QtTest, QtCore # Import the PySide module we'll need
import sys

class GUI(QtGui.QMainWindow):            # This class is to interact with the GUI
    def __init__(self):
        super(self.__class__, self).__init__()
        self.Kp_box = QtGui.QSpinBox(self)
        self.threadclass = ThreadClass(self)
        self.threadclass.start() 
        self.Kp_box.valueChanged.connect(self.kp_entry)     # Call function kp_entry if box value is changed

    def kp_entry(self):                                     # Run if kp is changed                  
        print("Main", self.Kp_box.value())                          # I WANT TO SEND THE BOX VALUE TO THE WORKER THREAD        

class ThreadClass(QtCore.QThread):                          # Infinite thread to communicate with robot
    def __init__(self, main_window):
        self.main_window = main_window
        super(ThreadClass, self).__init__(main_window)

    def run(self):
        while 1:             
            print(self.main_window.Kp_box.value())                       #CONTINUOUSLY PRINT THE UPDATED BOX VALUE    


def main():                             # Run the main GUI
    app = QtGui.QApplication(sys.argv)  # A new instance of QApplication
    form = GUI()                        # We set the form to be our ExampleApp 
    form.show()                         # Show the form
    app.exec_()                         # and execute the app

if __name__ == '__main__':              # if we're running file directly and not importing it
    main()                              # run the main function

我从你的代码中更改了什么:

  1. 我使用 PySide 而不是 PyQt,但它们大部分兼容(或者至少 他们应该是)。我不得不改变第一个导入 陈述;你将不得不把它改回来。
  2. 为了去除对 GUI 工具的依赖,我替换了你的 main window 有一个 SpinBox。这表明 多线程问题的基本特征并将其解耦 来自您的其他申请要求。
  3. 您的辅助线程无法访问 SpinBox,因为它没有 引用它的变量。我怀疑这是你的大问题 有。它通过将主 window 对象传递给 ThreadClass 构造函数并将其存储在实例变量中。

在任何意义上都不会从一个线程传输到另一个线程。这段代码只是利用了一个事实,即 Python 程序中的所有变量都位于同一内存 space 中,即使该程序是多线程的。 [如果程序使用多个 进程 ,则情况并非如此。]

这个小程序不提供任何正常关闭的方法。