tkinter: how to use after method tkinter: how to use after method tkinter tkinter

tkinter: how to use after method


You need to give a function to be called after the time delay as the second argument to after:

after(delay_ms, callback=None, *args)

Registers an alarm callback that is called after a given time.

So what you really want to do is this:

tiles_letter = ['a', 'b', 'c', 'd', 'e']def add_letter():    rand = random.choice(tiles_letter)    tile_frame = Label(frame, text=rand)    tile_frame.pack()    root.after(500, add_letter)    tiles_letter.remove(rand)  # remove that tile from list of tilesroot.after(0, add_letter)  # add_letter will run as soon as the mainloop starts.root.mainloop()

You also need to schedule the function to be called again by repeating the call to after inside the callback function, since after only executes the given function once. This is also noted in the documentation:

The callback is only called once for each call to this method. To keepcalling the callback, you need to reregister the callback insideitself

Note that your example will throw an exception as soon as you've exhausted all the entries in tiles_letter, so you need to change your logic to handle that case whichever way you want. The simplest thing would be to add a check at the beginning of add_letter to make sure the list isn't empty, and just return if it is:

def add_letter():    if not tiles_letter:        return    rand = random.choice(tiles_letter)    tile_frame = Label(frame, text=rand)    tile_frame.pack()    root.after(500, add_letter)    tiles_letter.remove(rand)  # remove that tile from list of tiles

Live-Demo: repl.it


I believe, the 500ms run in the background, while the rest of the code continues to execute and empties the list.

Then after 500ms nothing happens, as no function-call is implemented in the after-callup (same as frame.after(500, function=None))