Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tkinter's .after() and recursion

To update a widget in time I use the .after() method, usually in the following form:

def update():
    do_something()
    <widget>.after(<delay>, update)

It is my understanding that the widget waits for a certain amount of time and then executes the update() function, at the end of which the widget waits once again before re-executing the function and so on.

This seems to me a lot like recursion. So, the question is: Does .after() actually work by means of recursion or not?

If it does, then there is a limit to the depth of recursion, but the following example should prove that such limit is never reached:

from tkinter import *

counter = 0

def count():
    global counter
    counter += 1
    lbl.config(text=counter)
    root.after(10, count)

root = Tk()
lbl = Label(root, text='0')
lbl.pack()
Button(root, text='Start count', command=count).pack()
root.mainloop()

In my system the limit to the depth of recursion is 1000, but this example goes far beyond that value in a few seconds until I stop it.

like image 702
Pier Paolo Avatar asked Sep 03 '25 02:09

Pier Paolo


1 Answers

Recursion means that the current instance of a function is placed on hold and a new instance is created and run. after works differently, and is not recursion.

You can think of the mainloop as an infinite loop that maintains a todo list. The list has functions and the time that they ought to be run. The mainloop constantly checks the todo list and if an item in the todo list is due to be run, then the mainloop removes the item from the list and runs it. When it's done, it goes back to looping and checking the list. The after method just adds a function to this todo list along with a time to run it.

like image 86
Novel Avatar answered Sep 04 '25 20:09

Novel