[英]Tkinter: How to update a label text after a certain amount of time has passed?
[英]How to have Tkinter Label text change when after certain amount of time?
我正在設置一個GUI應用程序,並且在time.sleep()計時器上的Tkinter標簽上更改文本時遇到問題。
我已經嘗試過類似的東西
label_text = Label(main_window, text="hello world")
time.sleep(3)
label_text = Label(main_window, text="hello world")
(請注意,我有網格系統和tkinter窗口設置,我只是不會在其中顯示所有代碼)
# Currently this is not working how I would like it to, but here is the code
main_window = tkinter.Tk()
label_text = Label(main_window, text="hello world")
time.sleep(3)
label_text = Label(main_window, text="hello")
label_text.grid(column=1, row=1)
main_window.mainloop()
和這個
main_window = tkinter.Tk()
main_window.resizable(False, False)
main_window.geometry("500x900")
text = StringVar()
text.set("hello")
label = Label(main_window, text=text)
label.grid(column=1, row=1)
time.sleep(3)
text.set("anoefn")
main_window.update()
main_window.mainloop()
謝謝!
我認為這可以滿足您的需求。 您需要使用tk_obj.after來獲取時間延遲。 在問題代碼中,sleep將主循環的調用延遲3秒。
main_window = tk.Tk()
label_text = tk.Label(main_window, text="hello world")
def on_after():
label_text.configure( text="hello")
label_text.grid(column=1, row=1)
label_text.after(3000, on_after) # after 3000 ms call on_after
main_window.mainloop()
就像評論說的那樣,您可以使用鏈接到標簽的StringVar。 然后on_after將需要更改StringVar而不是配置標簽。
編輯:為了完整性,使用StringVar
main_window = tk.Tk()
var=tk.StringVar()
var.set("Hello World")
label_text = tk.Label(main_window, textvariable=var)
def on_after():
var.set("Hello ") # set the StringVar instead of configuring the label.
label_text.grid(column=1, row=1)
label_text.after(3000, on_after)
main_window.mainloop()
嘗試使用StringVar()數據類型
mytext = StringVar()
label_text = Label(main_window, text=mytext)
mytext.set("hello")
#after sometime change the text as required
mytext.set("new text")
希望這會起作用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.