I want to show a progress bar while downloading a file from the web using the urllib.urlretrive method.
How do I use the ttk.Progressbar to do this task?
Here is what I have done so far:
from tkinter import ttk
from tkinter import *
root = Tk()
pb = ttk.Progressbar(root, orient="horizontal", length=200, mode="determinate")
pb.pack()
pb.start()
root.mainloop()
But it just keeps looping.
For determinate mode you do not want to call
start. Instead, simply configure thevalueof the widget or call thestepmethod.If you know in advance how many bytes you are going to download (and I assume you do since you’re using determinate mode), the simplest thing to do is set the
maxvalueoption to the number you are going to read. Then, each time you read a chunk you configure thevalueto be the total number of bytes read. The progress bar will then figure out the percentage.Here’s a simulation to give you a rough idea:
For this to work you’re going to need to make sure you don’t block the GUI thread. That means either you read in chunks (like in the example) or do the reading in a separate thread. If you use threads you will not be able to directly call the progressbar methods because tkinter is single threaded.
You might find the progressbar example on tkdocs.com to be useful.