I’ve written a large program with nested classes/threads and multiple modules.
I would now like to add a simple GUI and some Labels to display some variables.
However, the variables are scattered throughout the modules and classes.
I’m looking for a way to update these variables into the GUI without altering
the current code too much.
I have a rudimentary understanding of Pyqt4 (i will accept tkinter answers also).
I’ve tried not to use signals/emits because to my knowledge emits
must be sent from a Qthread which would mean a complete overhaul of my code, changing
classes and threads over to Qthreads. Id like to avoid needing to do this if possible.
Here is one example I’ve attempted.
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_())
This code works, but my variables need to update from other modules/classes or threads. The moment I move ‘class Update’ into a new module like THIS:
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))
I get: AttributeError: 'module' object has no attribute 'wa'
Also, I was also considering putting class Update() into a Qthread, running it from any module/class where a variable has been updated and using the emit function inside Update(). this would solve having to change my current classes/threads to be Qthreads.
If anyone knows of a simple way I could update my GUI simply by calling a class like update() an example would be appreciated
Because
wais only set when__name__ == "__main__"and that only happens whentest.pyis the main file.When you do
import test, you are running another instance of thetest.pyfile which is not the main script so it has__name__ == 'test'not__main__. So, even ifwawas set, you would be changing another instance of it.Possible solution:
You can get a reference to the
__main__module and set on thetest2.pymodule:On test.py:
Now, on test2.py (do not import
testbut make suretestimportstest2):