繁体   English   中英

在 tkinter 中使用 'after' 方法的时间延迟独立工作

[英]time delay using 'after' method in tkinter works independently

考虑这个例子

from tkinter import *
history_text_list=[]
window=Tk()
window.geometry("1366x768+1+1")
winner_lbl=Label(window, text="0", fg='red', font=("Comic Sans MS", 96))
winner_lbl.place(x=5, y=5)
a_pixel = PhotoImage(width=1, height=1)
next_btn=Button(window, text="Next", font=("Comic Sans MS", 32), fg='blue', image=a_pixel, height = 70 , width = 130,compound="c")
next_btn.place(x=235, y=70)
history_text = StringVar()
history_label = Label(window, textvariable=history_text, wraplength=850, font=("Comic Sans MS", 16),justify="left",anchor="nw")
history_label.place(x=410, y=5)
def countdown(list_of_numbers):
    print('in function list-'+str(list_of_numbers))
    winner_lbl['fg'] = 'black'
    winner_lbl['text'] = list_of_numbers[0]
    list_of_numbers.pop(0)
    if list_of_numbers:
        window.after(500,countdown,list_of_numbers)
    else:
        winner_lbl['fg'] = 'red'
        return
def MyButtonClicked(self):
    one_to_hundred=list(range(1,10))
    countdown(one_to_hundred)
    history_text_list.append(10)
    history_text.set(str(history_text_list))
next_btn.bind('<Button-1>', MyButtonClicked)
window.mainloop()

在这里,按下下一步按钮时,您会注意到 label '0' 增加到 9,但 10 会快速添加到历史区域,尽管它应该在倒计时 function 结束后发生。
我应该怎么做才能确保串行执行?
谢谢。

after方法立即返回。 它不会等待超时到期。 当数字列表为空时,您应该将history_text.set调用放在countdown function 中。

顺便说一句,您可以使用if list_of_numbers而不是if len(list_of_numbers)==0来检查列表是否为空。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM