如何实时使用进度条小部件

How to use the Progressbar widget in real time

我有以下使用 Tkinter 小部件的代码:

from Tkinter import *
from ttk import Progressbar

root = Tk()

def addThoseNumbers():
    y = 0
    for x in range(1000000):
        y += x
        if x % 10000.0 == 0:
            invoiceStatus['value'] = x/10000.0
    print y

invoiceStatus = Progressbar(root, length = 280, mode = 'determinate')
invoiceStatus.pack()
invoiceButton = Button(root, text = "Confirm", font = ("Helvetica", 10), \
command = addThoseNumbers)
invoiceButton.pack()

root.mainloop()

理想情况下,进度条会在程序运行时更新以显示任务已完成的程度,但一旦任务完成,进度条就会从 0% 减少到 100%。如何编写我的程序以便进度条实时显示进度?

您只需添加 root.update()

from Tkinter import *
from ttk import Progressbar

root = Tk()

def addThoseNumbers():
    y = 0
    for x in range(1000000):
        y += x
        if x % 10000.0 == 0:
            invoiceStatus['value'] = x/10000.0
            root.update()
    print y

invoiceStatus = Progressbar(root, length = 280, mode = 'determinate')
invoiceStatus.pack()
invoiceButton = Button(root, text = "Confirm", font = ("Helvetica", 10), \
command = addThoseNumbers)
invoiceButton.pack()

root.mainloop()