Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I schedule updates (f/e, to update a clock) in tkinter?

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.

like image 711
Diego Castro Avatar asked Mar 08 '10 09:03

Diego Castro


People also ask

Can you use time sleep in tkinter?

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.

What does tkinter Update () do?

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.

What is FG in tkinter widget means?

foreground − Foreground color for the widget. This can also be represented as fg.


1 Answers

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.

like image 151
Bryan Oakley Avatar answered Oct 10 '22 10:10

Bryan Oakley