1
votes

I'm trying to make a GUI where the user clicks a button and the app downloads a file from the internet. I want to have a progress bar showing how long until the file download is complete. To achieve this I have implemented a thread to run the progress bar's function when the download button is clicked. Here is the code I'm using:

def progthread():
    threading.Thread(target=download).start()

def download():
    blocknum = 0
    blocksize = 0
    url = "https://www.python.org/static/img/python-logo.png"
    filename = "C:\My Python Apps\MyFile.png"
    response = requests.get(url, stream=True)
    total_length = response.headers.get('content-length')

    with open(filename, "wb") as f:
        for data in response.iter_content(chunk_size=10000):
            f.write(data)
            percent = int(blocknum * blocksize / int(total_length))

            progress['value'] = percent 

When I run the application, it downloads the file and no errors come up. But the progress bar does not do anything. I tried using progress.update() and progress.update_idletask() but the progress bar was still not working.

How can I get the progressbar to show the download progress of the file?

1
You've not assigned values to blocknum and blocksize within the loop, so they're always stuck at 0. - Harshith Thota

1 Answers

1
votes

The problem is that the loop you have blocks tkinter's mainloop, so the whole GUI locks up. For something like this you should launch the download loop in a separate thread so that it can run at the same time as the tkinter mainloop. You can use a tkinter IntVar to update the progress bar from the other thread.

If you update your question with a Minimal, Complete, and Verifiable example then I can help you implement that.