我正在構建一個獲取日期和時間的簡單程式。我能夠獲得正確的值,但我無法更新畫布中的值。這是我獲取溫度的函式。
from time import strftime
def my_time():
time_string = strftime('%H:%M:%S %p') # time format
return time_string
time = my_time()
canvas.create_text(
1068.0,
744.0,
anchor="nw",
text=time,
fill="#FFFFFF",
font=("Poppins Bold", 120 * -1)
)
window.resizable(False, False)
window.mainloop()
我按照本教程進行操作,但我沒有使用他們使用的標簽。我想使用 canvas.create_text。https://www.plus2net.com/python/tkinter-clock.php
如何確保時間每秒自動更新?我嘗試過執行緒,我嘗試過 .after(1000, functionName) 但仍然如此。我是python新手,所以請對答案寬容。
在我的代碼中,我有一個單獨的函式用于從傳感器獲取溫度,我能夠獲取溫度,但我也需要每秒更新一次。但我相信如果我能做到這一點,我也能得到它的溫度。
這是獲取溫度的代碼。
def read_temp_raw():
with open(device_path '/w1_slave','r') as f:
valid, temp = f.readlines()
return valid, temp
def read_temp():
global c
valid, temp = read_temp_raw()
while 'YES' not in valid:
time.sleep(0.2)
valid, temp = read_temp_raw()
pos = temp.index('t=')
if pos != -1:
#read the temperature .
temp_string = temp[pos 2:]
temp_c = float(temp_string)/1000.0
temp_c = round(temp_c, 2)
temp_f = temp_c * (9.0 / 5.0) 32.0
temp_f = round(temp_f, 2)
return temp_c, temp_f
c, f = read_temp()
canvas.create_text(
696.0,
127.0,
anchor="nw",
text=c,
fill="#FFFFFF",
font=("Poppins Bold", 309 * -1)
)
uj5u.com熱心網友回復:
文本物件的 ID 由 回傳create_text。保存并使用它來更改文本canvas.itemconfig:
def update_temp():
c, _ = read_temp()
canvas.itemconfig(temp_text_id, text=str(c))
canvas.after(1000, update_time)
c, f = read_temp()
temp_text_id = canvas.create_text(
1068.0,
744.0,
anchor="nw",
text=str(c),
fill="#FFFFFF",
font=("Poppins Bold", 120 * -1)
)
canvas.after(1000, update_temp)
window.mainloop()
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/409456.html
標籤:
