如何更新循环中的进度条?

时间:2016-04-09 12:03:21

标签: python python-2.7 user-interface tkinter

在循环中更新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()

1 个答案:

答案 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()