无按钮填充进度条
我正在尝试制作一个进度条,想让它在窗口打开时自动开始填充。
所以我没有做一个按钮来触发填充进度条的功能,而是直接调用这个填充的函数。结果让我意外的是,窗口一开始是空的,过了5秒(填充进度条的时间)后,进度条才显示为填满。
问题是,当我用按钮替换这个填充函数时,它就能正常工作。那么,为什么直接调用这个函数不行呢?我该如何让它在没有按钮的情况下也能填充呢?
我的代码:
from tkinter import *
from tkinter import ttk as ttk
from time import *
def fill():
t = 100
x = 0
s = 1
while x <= t:
bar['value'] += s
x += s
sleep(0.05)
window2.update_idletasks()
def read():
global window2
window2 = Tk()
global bar
bar = ttk.Progressbar(window2,orient=HORIZONTAL,length=300)
bar.pack(pady=15)
fill() # here I replace the function with a button calling it and it works well but I don't want a button
window2.mainloop()
read()
1 个回答
1
你的问题是因为在 tkinter
中使用了 time.sleep
。
应该改用 after
调度器。
下面的代码修改和注释展示了一种实现方法。
from tkinter import *
from tkinter import ttk as ttk
def fill(s, c):
c = c + 1
# Update progressbar
bar['value'] = c
# Test for exit conditions
if c <= s:
# Repeat action recursively by passing current values back to itself
window2.after(50, fill, s, c)
else:
bar.destroy()
# Ready to continue creating other widgets
def read():
global window2
window2 = Tk()
global bar
delay, steps, count = 50, 100, 0
# Include the maximum step value `steps` for given length
bar = ttk.Progressbar(window2, orient = HORIZONTAL, length = 300, maximum = steps)
bar.pack(pady=15)
# Begin by using `after` scheduler with `delay` to pass `steps` and `count` to `fill` function
window2.after(delay, fill, steps, count)
window2.mainloop()
read()