Tkinter: ProgressBar with undefined duration

I would like to implement a progress bar in Tkinter that satisfies the following requirements:

  • The progress bar is the only item in the main window
  • It can be started by the run command without having to press any button
  • He can wait for the completion of a task with an unknown duration
  • The progress bar continues to move until the task is complete.
  • It can be closed by a stop command without having to press any stop panel

So far, I have the following code:

import Tkinter
import ttk
import time

def task(root):
    root.mainloop()

root = Tkinter.Tk()
ft = ttk.Frame()
ft.pack(expand=True, fill=Tkinter.BOTH, side=Tkinter.TOP)
pb_hD = ttk.Progressbar(ft, orient='horizontal', mode='indeterminate')
pb_hD.pack(expand=True, fill=Tkinter.BOTH, side=Tkinter.TOP)
pb_hD.start(50)
root.after(0,task(root))
time.sleep(5) # to be replaced by process of unknown duration
root.destroy()

      

The problem here is that the progress bar doesn't stop after 5 seconds has finished.

Can anyone help me find the error?

+3


source to share


1 answer


When mainluop is active, the script will not move to the next line until the root is destroyed. There may be other ways to do this, but I'd rather do it with streams.

Something like that,



import Tkinter
import ttk
import time
import threading

#Define your Progress Bar function, 
def task(root):
    ft = ttk.Frame()
    ft.pack(expand=True, fill=Tkinter.BOTH, side=Tkinter.TOP)
    pb_hD = ttk.Progressbar(ft, orient='horizontal', mode='indeterminate')
    pb_hD.pack(expand=True, fill=Tkinter.BOTH, side=Tkinter.TOP)
    pb_hD.start(50)
    root.mainloop()

# Define the process of unknown duration with root as one of the input And once done, add root.quit() at the end.
def process_of_unknown_duration(root):
    time.sleep(5)
    print 'Done'
    root.destroy()

# Now define our Main Functions, which will first define root, then call for call for "task(root)" --- that your progressbar, and then call for thread1 simultaneously which will  execute your process_of_unknown_duration and at the end destroy/quit the root.

def Main():
    root = Tkinter.Tk()
    t1=threading.Thread(target=process_of_unknown_duration, args=(root,))
    t1.start()
    task(root)  # This will block while the mainloop runs
    t1.join()

#Now just run the functions by calling our Main() function,
if __name__ == '__main__':
    Main()

      

Let me know if it helps.

+3


source







All Articles