hey everyone, i am writting an app with tkinter, well ive tried quite alot of different ways but i couldnt find the solution for my problem. So, in that window there is time and i need it to constantly change, like every second. Any ideas? Thanks Dan08

Dani AI

Generated

A few key Tkinter patterns will make a ticking clock reliable and keep the rest of your UI responsive:

  • Create exactly one Tk() per app and keep a reference to it. In your first snippet you instantiate Tk() twice; that can lead to widgets being garbage collected and errors like TclError: invalid command name ".53252544".
  • Avoid while True + time.sleep() + root.update(). sleep() blocks the event loop, and update() can cause hard-to-debug re-entrancy issues. Schedule periodic work with after(), which integrates with the mainloop.

Minimal pattern using after() without a class:

import Tkinter as tk  # use 'import tkinter as tk' on Python 3
import time

root = tk.Tk()
lbl = tk.Label(root, font=("Helvetica", 12))
lbl.pack(padx=10, pady=10)

def tick():
    lbl.config(text=time.strftime("%d/%m/%Y %A %H:%M:%S"))
    root.after(1000, tick)  # schedule next update in 1s

tick()
root.mainloop()

Tips:

  • If you later need to stop updates (e.g., when closing a window), store the id from after() and cancel it with after_cancel().
  • If you update the UI from worker threads, marshal back to the main thread using root.after(...).

References:

Recommended Answers

All 7 Replies

Member Avatar for Member #562630

hey everyone, i am writting an app with tkinter, well ive tried quite alot of different ways but i couldnt find the solution for my problem. So, in that window there is time and i need it to constantly change, like every second. Any ideas? Thanks Dan08

hi,
could you be more specific about what you're trying to do, e.g. provide your code so far, or some example, cause it's not very clear :)
Are you trying to make a clock or something?

P.S sorry if I'm missing something

The answer is in your title, but you should give us your code to make things clear.

The code of the whole program is enormous, so i just made it smaller:

from Tkinter import *
import time
Label(Tk(), text=time.strftime("%d/%m/%Y %A %H:%M:%S")).pack()
Tk().mainloop()

Now when i run this, i need to see the time changing. Any ideas, thanks dan08.

Member Avatar for Member #562630

that's much clearer :) thanks

here's one way of doing this:

from Tkinter import *
import time

root = Tk()
l = Label( root, text=time.strftime( "%d/%m/%Y %A %H:%M:%S") )
l.pack()
root.update()

while True:
    time.sleep( 1 )
    l[ "text" ]=time.strftime( "%d/%m/%Y %A %H:%M:%S" )
    root.update()
    
mainloop()

of course you could make this into a separate thread as well :)

Isn't there anyother way coz when i try the masterofpuppets' code it keeps giving me this error:

Traceback (most recent call last):
  File "C:\Users\Dan08\Desktop\program.py", line 11, in <module>
    l[ "text" ]=time.strftime( "%d/%m/%Y %A %H:%M:%S" )
  File "C:\Python26\lib\lib-tk\Tkinter.py", line 1209, in __setitem__
    self.configure({key: value})
  File "C:\Python26\lib\lib-tk\Tkinter.py", line 1202, in configure
    return self._configure('configure', cnf, kw)
  File "C:\Python26\lib\lib-tk\Tkinter.py", line 1193, in _configure
    self.tk.call(_flatten((self._w, cmd)) + self._options(cnf))
TclError: invalid command name ".53252544"

It works, but when i run other parts of the program dont work, like the title and so on. Any ideas, Dan08.

For timed events you generally use the "after" function.

from Tkinter import *
import datetime
import time

class ChangeTime(Frame):

    def __init__(self, master=None):
        master.geometry("100x50+5+5")
        Frame.__init__(self, master)
        self.pack()

        self.timestr = StringVar()
        lbl = Label(master, textvariable=self.timestr)
        lbl.pack()

        # register callback
        self.listenID = self.after(1000, self.newtime)

    def newtime(self):
        timenow = datetime.datetime.now()
        self.timestr.set("%d:%02d:%02d" % \  
                 (timenow.hour, timenow.minute, timenow.second))
        self.listenID = self.after(1000, self.newtime)


root=Tk()
CT = ChangeTime(root)
CT.mainloop()

I dont really know how to put it working, any help please!! woooee's method is working but i dont know how to put his code into the massive lines of code. Dan08

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.