在循环中更新Tkinter进度条的简单方法是什么?
我需要一个没有太多混乱的解决方案,所以我可以在我的脚本中轻松实现它,因为它对我来说已经很复杂了。
让我们说代码是:
from Tkinter import *
import ttk
root = Tk()
root.geometry('{}x{}'.format(400, 100))
theLabel = Label(root, text="Sample text to show")
theLabel.pack()
status = Label(root, text="Status bar:", bd=1, relief=SUNKEN, anchor=W)
status.pack(side=BOTTOM, fill=X)
root.mainloop()
def loop_function():
k = 1
while k<30:
### some work to be done
k = k + 1
### here should be progress bar update on the end of the loop
### "Progress: current value of k =" + str(k)
# Begining of a program
loop_function()
答案 0 :(得分:5)
以下是持续更新ttk
进度条的快速示例。您可能不希望将sleep
放在GUI中。这只是为了减慢更新速度,以便您可以看到它的变化。
from Tkinter import *
import ttk
import time
MAX = 30
root = Tk()
root.geometry('{}x{}'.format(400, 100))
progress_var = DoubleVar() #here you have ints but when calc. %'s usually floats
theLabel = Label(root, text="Sample text to show")
theLabel.pack()
progressbar = ttk.Progressbar(root, variable=progress_var, maximum=MAX)
progressbar.pack(fill=X, expand=1)
def loop_function():
k = 0
while k <= MAX:
### some work to be done
progress_var.set(k)
k += 1
time.sleep(0.02)
root.update_idletasks()
root.after(100, loop_function)
loop_function()
root.mainloop()