Reputation: 119
I am trying to make a digital clock in python, I think I did everything right but the Canvas isn't refreshing so it just stays on 1 position.
import tkinter
import datetime
canvas = tkinter.Canvas(width=640, height=480)
canvas.pack()
t = datetime.datetime.now()
current_time = t.strftime("%H:%M:%S.%f")[:-5]
hour = t.hour
minute = t.minute
second = t.second
mc = t.microsecond
micro = mc/100000
print(current_time)
def tick():
global current_time, micro, second, minute, hour
micro += 1
canvas.after(100, tick)
if micro > 9:
second += 1
tick
if second > 59:
minute += 1
tick
if minute > 59:
hour += 1
tick
if hour > 23:
hour = 0
tick
clock = canvas.create_text(320, 240, font="arial 72", text=current_time)
canvas.itemconfig(clock, text=current_time)
canvas.mainloop()
Can I do it like this or do I need to label the canvas?
Upvotes: 0
Views: 284
Reputation: 386210
You have to reconfigure the canvas item whenever you want it to change (eg: canvas.itemconfigure(clock, text=...)
). Also, you have to call tick
once to start the loop.
For a simple clock, there's no need to calculate the hours, minutes and seconds. It is simpler to just ask python for the current time each time the function is called.
Example:
import tkinter
import datetime
canvas = tkinter.Canvas(width=640, height=480)
canvas.pack()
def tick():
t = datetime.datetime.now()
current_time = t.strftime("%H:%M:%S.%f")[:-5]
canvas.itemconfigure(clock, text=current_time)
canvas.after(100, tick)
clock = canvas.create_text(320, 240, font="arial 72")
tick()
canvas.mainloop()
Upvotes: 1