I'm writing a program with Python's tkinter library.
My major problem is that I don't know how to create a timer or a clock like hh:mm:ss
.
I need it to update itself (that's what I don't know how to do); when I use time.sleep()
in a loop the whole GUI freezes.
In this case, your application will print a string to stdout after 3 seconds. You can think of after() as the tkinter version of time. sleep() , but it also adds the ability to call a function after the sleep has finished. You could use this functionality to improve user experience.
Python Tkinter Mainloop Update Update() method in mainloop in Python Tkinter is used to show the updated screen. It reflects the changes when an event occurs.
foreground − Foreground color for the widget. This can also be represented as fg.
Tkinter root windows have a method called after
which can be used to schedule a function to be called after a given period of time. If that function itself calls after
you've set up an automatically recurring event.
Here is a working example:
# for python 3.x use 'tkinter' rather than 'Tkinter' import Tkinter as tk import time class App(): def __init__(self): self.root = tk.Tk() self.label = tk.Label(text="") self.label.pack() self.update_clock() self.root.mainloop() def update_clock(self): now = time.strftime("%H:%M:%S") self.label.configure(text=now) self.root.after(1000, self.update_clock) app=App()
Bear in mind that after
doesn't guarantee the function will run exactly on time. It only schedules the job to be run after a given amount of time. It the app is busy there may be a delay before it is called since Tkinter is single-threaded. The delay is typically measured in microseconds.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With