Reputation: 13
So, I need to print the current time within my program (Tkinter GUI application), but I'm facing an issue where it will only print the time I ran the script, and not update to the current time. So, for example, I need a Start time and End time, but both end up being the timestamp of when I ran the script. Here is what I am using currently. Is it possible to update the variables to show the current time without restarting the script?
now = datetime.now()
now2 = datetime.now()
current_time = ""
current_time2 = ""
current_time += now.strftime("%H:%M %p")
StartTime = current_time
current_time2 += now2.strftime("%H:%M %p")
EndTime = current_time2
Upvotes: 0
Views: 54
Reputation: 142631
It was so many times - you have to use after()
to run periodically function which will update it
import tkinter as tk
import time
# --- functions ---
def update_time():
label['text'] = time.strftime('%Y.%m.%d %H:%M:%S')
# run update_time again after 1000ms (1s)
root.after(1000, update_time) # function's name without `()`
# --- main ---
root = tk.Tk()
label = tk.Label(root)
label.pack()
# run update_time first time
update_time()
# start program
root.mainloop()
Upvotes: 1