所以我试图制作一个进度条,当 窗户打开了.. 因此,不要制作一个按钮,按下时调用填充功能 我直接调用该函数的栏,出乎我意料的是它显示了一个空 窗口,5 秒后(填充条形的时间),条形显示已填充 问题是,当我用按钮替换 fill() 时,它可以正常工作 那么为什么它不能仅仅通过调用函数来工作以及如何让它填充 没有按钮 我的代码:
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()
您的问题是由于在
time.sleep
中使用 tkinter
引起的。
请使用
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()