[英]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.