簡體   English   中英

Tkinter 更新 label 中的變量

[英]Tkinter update a variable in a label

任何人都可以幫助解決這個問題或指出我正確的方向嗎?

我正在使用 Python 3.9.7

我的目標是創建一個 python 程序,該程序使用 Tkinter 顯示兩個變量之間的時間增量,我希望這個變量在倒計時時每秒更新一次。

I have created the TK window, with my header text and timedif label appearing inside, however while my program runs the timedif label does not update. Timedif label 只顯示程序執行時的時間增量。

我定義了一個 function countdown_update 打算使用 .after 方法每 1000 毫秒更新一次倒計時,然后包含一個打印語句以直觀地看到 function 被調用。 可以在終端看到打印語句,我的label沒有更新。 我不確定如何解決這個問題。

'''

from tkinter import * 
from datetime import datetime


#datetime.date = Year, Month, Day
#datetime.time = hour, minute, second
#datetime.datetime = Y,M,D,H,M,S,MS

#Declaration of variables
future_day = datetime(2022, 1, 7, 17, 0, 0, 555555)
today = datetime.today()
timediff = future_day - today

#Creating the TK Window
window = Tk()

# setting geometery of the window
window.geometry("500x300")

#Using title() to display a message in the dialogue box of the message in the title bar
window.title("Time until future day")

#adding a label to the window
Header = Label(window, background="black", text="Time Remaining", bg="purple", 
fg="black", font="none 24 bold")
Header.config(anchor=CENTER)
Header.pack(pady=20, ipadx=10, ipady=10)

#adding the timer to the window
timedif_label = Label(window, text=timediff, bg="black", fg="purple", font="none 28 
bold")
timedif_label.config(anchor=CENTER)
timedif_label.pack(pady=20,padx=20)

def countdown_update():
    timedif_label.after(1000, countdown_update)
    print("update finished")


#execute Tkinter
countdown_update()
window.mainloop()
    

'''

任何幫助將不勝感激,謝謝。

更改 tkinter 文本不是通過引用“正常”變量來完成的。 Tkinter 針對這種情況提供了自己的變量版本。

因此,要更改文本,您將使用 StringVar()。 在您的情況下,我建議您像這樣更改 timediff var:

timediff = tk.StringVar(str(future_day - today))

像這樣改變你的 Label (注意“文本”現在是“文本變量”):

timedif_label = Label(window, textvariable=timediff, bg="black", fg="purple", font="none 28 
bold")

最后像這樣改變你的 countdown_update :

def countdown_update():
    timediff.set(str(new_time)) #insert calculations here
    timedif_label.after(1000, countdown_update)   
    print("update finished")

所以你設置 tkinter StringVar 然后這應該改變你的 label 中顯示的文本

有關更多詳細信息,您可以查看: https://www.delftstack.com/howto/python-tkinter/how-to-change-the-tkinter-label-text/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM