【问题标题】:Python 3 pyQt4 updating GUI with variables from multiple modules/classesPython 3 pyQt4 使用来自多个模块/类的变量更新 GUI
【发布时间】:2012-06-10 00:29:33
【问题描述】:

我编写了一个包含嵌套类/线程和多个模块的大型程序。 我现在想添加一个简单的 GUI 和一些标签来显示一些变量。 但是,变量分散在整个模块和类中。 我正在寻找一种方法将这些变量更新到 GUI 中而不改变 当前代码太多。

我对 Pyqt4 有基本的了解(我也会接受 tkinter 的答案)。

我尝试不使用信号/发射器,因为据我所知发射器 必须从 Qthread 发送,这意味着对我的代码进行彻底检查,更改 类和线程转移到 Qthreads。如果可能的话,我想避免这样做。 这是我尝试过的一个例子。

test.py

class Update(Thread): 
    def __init__(self): 
        Thread.__init__(self) 
    def run(self): 

        for i in range(10): 
            time.sleep(2) 
            import test 
            wa.label.setText(str(i)) 

class MyWindow(QWidget):  
    def __init__(self, *args):  
        QWidget.__init__(self, *args) 

        self.label = QLabel(" ") 
        layout = QVBoxLayout() 
        layout.addWidget(self.label) 
        self.setLayout(layout) 

        Update1 = Update() 
        Update1.start() 
        Update1.refresh1 = 'ba' 

        self.label.setText(Update1.refresh1) 


if __name__ == "__main__":  
    app = QApplication(sys.argv)  
    wa = MyWindow()  
    wa.show()  
    sys.exit(app.exec_()) 

此代码有效,但我的变量需要从其他模块/类或线程更新。当我将“类更新”移动到这样的新模块中时:

test.py

import test2 


class MyWindow(QWidget):  
    def __init__(self, *args):  
        QWidget.__init__(self, *args) 

        self.label = QLabel(" ") 
        layout = QVBoxLayout() 
        layout.addWidget(self.label) 
        self.setLayout(layout) 

        Update1 = test2.Update() 
        Update1.start() 
        Update1.refresh1 = 'ba' 

        self.label.setText(Update1.refresh1) 


if __name__ == "__main__":  
    app = QApplication(sys.argv)  
    wa = MyWindow()  
    wa.show()  
    sys.exit(app.exec_()) 

test2.py #updates GUI

class Update(Thread): 
    def __init__(self): 
        Thread.__init__(self) 
    def run(self): 

        for i in range(10): 
            time.sleep(2) 
            import test 
            test.wa.label.setText(str(i)) 

我得到:AttributeError: 'module' object has no attribute 'wa'

此外,我还考虑将类 Update() 放入 Qthread,从任何已更新变量的模块/类运行它,并使用 Update() 中的 emit 函数。这将解决必须将我当前的类/线程更改为 Qthreads 的问题。

如果有人知道我可以通过调用类似 update() 的类来更新我的 GUI 的简单方法,我们将不胜感激

【问题讨论】:

    标签: python python-3.x tkinter pyqt4


    【解决方案1】:

    因为wa 仅在__name__ == "__main__" 时设置,并且仅在test.py 是主文件时发生。

    当您执行import test 时,您正在运行不是主脚本的test.py 文件的另一个实例,因此它具有__name__ == 'test' 而不是__main__。因此,即使设置了wa,您也会更改它的另一个实例。

    可能的解决方案:

    您可以获得对__main__ 模块的引用并在test2.py 模块上进行设置:

    test.py 上:

    import test2
    test2.parent = sys.modules[__name__]
    

    现在,在 test2.py 上(不要导入 test,但要确保 test 导入 test2):

    parent.wa.label.setText('Blablabla')
    

    【讨论】:

      猜你喜欢
      • 2012-06-20
      • 2016-06-27
      • 2018-08-31
      • 1970-01-01
      • 1970-01-01
      • 2014-08-18
      • 1970-01-01
      • 1970-01-01
      • 2014-06-22
      相关资源
      最近更新 更多