import sys
import ttk
from Tkinter import *
from timeit import default_timer as timer
def sum(a, b):
for i in range(10):
c = a + b
print "Sum", c
time.sleep(5)
return c
mGui = Tk()
mGui.title('Progress')
mpb = ttk.Progressbar(mGui,orient ="horizontal", length = 200, mode ="determinate")
mpb.pack()
mpb.start()
mpb["maximum"] = 100
Start_Timer=timer()
sum(3,4)
Stop_Timer=timer()
Execution_Time=Stop_Timer-Start_Timer
mpb["value"] = Execution_Time
mGui.mainloop()
I have a function which calculates the sum of two integers. I want to display the status of the execution of this sum function using tkinter progress bar.
This is my approach, but it displays progress bar after executing the sum
function, and I want to display the progress bar while the sum
function is executing, and the progress should be indicated based on the execution time of the function.
I didn't find answers which satisfy my requirement. It would be great if someone could help me with this.
You question is interesting, but you approach is totally wrong. It executes your
sum
first, because the GUI has not reachedmainloop
.So after GUI reaches
mainloop
it start to wait for events (because of event-driven nature of GUI programming) like button presses. In other words: you can't call a function untilmainloop
if you ask for callbacks to tkinter.Another problem - tkinter is single threaded so the gui can only update itself when the function finishes running. So if you start a loop in function there's no callbacks to gui either, but you can call function from a loop, and update gui on each iteration! (e.g. "Loop" of self generated events, consisting of the methods
generate_event
orafter
.)And for god's sake how progressbar can know execution time of a function if function isn't completely executed? If anybody knows that, please comment..
But if you dare, you can start playing with multithreading and queues!
In my example, the progress bar is updated in parallel with the execution of the function, thanks to the separate thread in which the function is executed, and the queue to which the "responses" of the function fall, on the basis of which the progress bar is updating!
Tested it with python 3.5:
Links: