我已经制作了一个用于从网站下载多个文件的 python 脚本,我想在 Tkinter 中制作一个进度条,它应该随着每个文件保存到计算机而更新。我看过一些使用 OOP 的例子,但我仍然在掌握 OOP,并且希望有一天能理解为什么人们在 Tkinter 中制作 GUI 应用程序时使用 OOP。也许好心的用户可以为我澄清这一点。
我的代码显示在这里:
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()
我创建了一个代表文件数量的变量(我并不是真的要下载 1000000 个文件,这只是一些让进度条正常工作的代码)。
代码应该在单击开始按钮时运行加载函数,但实际上没有。如果您能在这个问题上给我任何帮助,我将不胜感激 =)
最佳答案
在事件驱动编程 (GUI) 中,您不能使用像 for 循环这样的阻塞循环。您必须使用 after
设置事件才能再次运行函数。这与迭代器结合得很好:
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()
关于python - 更新 Tkinter 进度条,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50496347/