Home > Software engineering >  How to update Tkinter's progressbar with urlretrieve?
How to update Tkinter's progressbar with urlretrieve?

Time:10-10

What i want to do is a program that downloads a file from a URL with a given filename and see its progress with a progressbar but when i launch the dl function , the progressbar doesn't move.

Can you please help me with updating the progressbar in relation to urlretrieve's reporthook function?

Code below :

import tkinter as tk
import tkinter.ttk as ttk
from urllib.request import urlretrieve

window = tk.Tk()
window.geometry('300x300')
window.minsize(300, 300)
window.maxsize(300, 300)
window.title('Downloader')

lbl_url = tk.Label(window)
lbl_url.configure(text='URL', font='{Arial} {9}')
lbl_url.pack()

ent_url = tk.Entry(window)
ent_url.configure(font='{Arial} {9}')
ent_url.pack()

lbl_file = tk.Label(window)
lbl_file.configure(text='Filename', font='{Arial} {9}')
lbl_file.pack()

ent_file = tk.Entry(window)
ent_file.configure(font='{Arial} {9}')
ent_file.pack()

progressbar = ttk.Progressbar(window)
progressbar.configure(length=225, orient='horizontal', mode='determinate', maximum=100)
progressbar.pack(side='bottom', pady=10, padx=10)


def report(count, block_size, total_size):
    value = 0
    while value <= 100.0:
        progress_size = float(count * block_size)
        percent = float(progress_size * 100 / total_size)
        value = percent
        progressbar['value'] = value
        time.sleep(0.1)
        window.update()


def dl():
    urlretrieve(ent_url.get(), ent_file.get(), report)


btn_dl = tk.Button(window)
btn_dl.configure(text='Download', font='{Arial} {9}', command=dl)
btn_dl.pack(side='bottom')

window.mainloop()```

CodePudding user response:

What is the purpose of this while value <= 100.0: loop?

After a chunk is downloaded, the report() function will be called. We do not need to run a while loop.

Here is the working report() -

def report(count, block_size, total_size):
    progress_size = count * block_size
    percent = progress_size * 100 / total_size
    progressbar['value'] = percent
    window.update()
  • Related