简体   繁体   中英

Update Tkinter progress bar

I've made a python script for downloading a number of files from a website and I'd like to make a progress bar in Tkinter which should update as each file is saved to the computer. I've seen some examples using OOP but I'm still getting to grips with OOP and one day hope to understand why people use OOP when making GUI apps in Tkinter. Perhaps a kind user could clarify this for me.

My code is shown here:

from Tkinter import *
import ttk
import numpy as np

global files
files = np.arange(1,1000000)

def loading():
    global downloaded
    downloaded = 0
    for i in array:
        downloaded +=1

root = Tk()

progress= ttk.Progressbar(root, orient = 'horizontal', maximum = 1000000, value = downloaded, mode = 'determinate')
progress.pack(fill=BOTH)
start = ttk.Button(root,text='start',command=loading)
start.pack(fill=BOTH)

root.mainloop()

I've made a variable which represents the number of files (I'm not really trying to download 1000000 files, this was just some code to get the progress bar working).

The code should run the loading function when the start button is clicked but it doesn't. I'd greatly appreciate any help you can give me on this issue =)

In event driven programming (GUIs) you can't have a blocking loop like your for loop. You have to set an event using after to run a function again. This marries well with iterators:

from Tkinter import *
import ttk
import numpy as np

root = Tk()

files = iter(np.arange(1,10000))


downloaded = IntVar()
def loading():
    try:
        downloaded.set(next(files)) # update the progress bar
        root.after(1, loading) # call this function again in 1 millisecond
    except StopIteration:
        # the files iterator is exhausted
        root.destroy()

progress= ttk.Progressbar(root, orient = 'horizontal', maximum = 10000, variable=downloaded, mode = 'determinate')
progress.pack(fill=BOTH)
start = ttk.Button(root,text='start',command=loading)
start.pack(fill=BOTH)

root.mainloop()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM