I am building a simple program that gets date and time. I am able to get the values alright, but i am unable to update the values in the canvas. Here is my function that gets the temperature.
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()
I followed this tutorial, but i am not using the labels they used. I want to use the canvas.create_text. https://www.plus2net.com/python/tkinter-clock.php
How do i make sure the time automatically updates every second? I have tried threading, i have tried .after(1000, functionName) but still. I am new to python so kindly be lenient with the answer.
In my code, i have a separate function for getting the temperature from a sensor, I am able to get the temperature, but i need to update that every second too. But i believe if i am able to do it for the time, i can get it for the temperature too.
Here is the code for getting the temperature.
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)
)
CodePudding user response:
The ID of the text object is returned by create_text. Save it and use it to change the text with 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()
