Reputation: 401
In an app with two modules: GUI.py and calcs.py, where GUI imports and uses functions from calcs, what is a good way for a calcs function to update a progress bar in GUI?
It used to be simple when I had all my code in one module. I refactored it into two (still learning...) and this is the only thing I now can't fix.
e.g. as a very simple example, the GUI.py module having:
import tkinter as tk
import tkinter.ttk as ttk
import calc as c
class GUI(tk.Tk):
def __init__(self):
tk.Tk.__init__(self)
self.prog = tk.DoubleVar()
self.result = tk.StringVar()
self.label = ttk.Label(textvariable = self.result)
self.progbar = ttk.Progressbar(self, maximum = 10, variable = self.prog)
self.button= ttk.Button(self, text = 'Go', command = lambda: self.result.set(c.stuff()))
self.label.pack()
self.progbar.pack()
self.button.pack()
a = GUI()
a.mainloop()
and the calc.py having:
def stuff():
counter = 0
for i in range(1, 11, 1):
counter += 1
# find a way to pass the value of counter to the GUI progress bar
# do lots of stuff that takes quite some time
return 'hey, a result!'
What's a good way to link the progress counter in the calc function with the progress bar variable in the GUI?
When they were in one module together it was simple enough of course - could just call
prog.set(counter)
a.update_idletasks()
but no longer. Googling and reading about this I tried making it threaded and using a queue to link them but this a) seemed like overkill and b) was difficult... I did not get it working...
Upvotes: 1
Views: 101
Reputation: 385960
Create a function in your GUI module that updates the progress bar, and give a reference to that function as an argument to your calc functions:
# GUI.py
class GUI(...):
def __init__(...):
...
self.button= ttk.Button(..., command = lambda: c.stuff(self))
...
def update_progress(self):
...
# calc.py
def stuff(gui):
for i in range(...):
...
gui.update_progress()
Upvotes: 1