如何使用 tkinter configure 每次循环更新标签。下面的代码只显示最终的循环字符串

How can I update the label everytime in loop with tkinter configure. Below code only displaying the final loop string

from tkinter import *
import time

win = Tk()
def call():
    for i in range(5, 0, -1):
        time.sleep(1)
        l1.configure(text = str(i) + " seconds left")

l1 = Label(win, text = "Timer")
l1.pack()

b1 = Button(win, text = "Click", command = call)
b1.pack()

win.mainloop()

此代码正在等待 4 秒并仅给出最终循环值

这是 tkinter 的问题,因为我们正在使用我猜的时间模块,我绕过的方法是更改​​ window 的名称这是代码,您也可能想使用 f字符串:

from tkinter import *
import time

win = Tk()
win.geometry('300x400')

def call():
    for i in range(5, 0, -1):
        i -= 1
        time.sleep(1)
        win.title(f'{i} seconds left')

l1 = Label(win, text = "Timer")
l1.pack()

b1 = Button(win, text = "Click", command = call)
b1.pack()

win.mainloop()
from tkinter import *
# import time

win = Tk()
def call():
    for i in range(5, 0, -1):
        win.update()                     # gets updated everytime
        l1.configure(text = str(i) + " seconds left")
        win.after(1000)                  # sleep for a second
   
l1 = Label(win, text = "Timer")
l1.pack()

b1 = Button(win, text = "Click", command = call)
b1.pack()

win.mainloop()

此代码有效..

不建议在 tkinter 应用程序中使用 time.sleep()。使用 .after() 代替:

def call(i=5):
    l1.configure(text=f"{i} seconds left")
    if i > 0:
        l1.after(1000, call, i-1)