I've seen numerous question on this site, where people ask how user-written code, say a function foo
, can be executed in tkinter's mainloop
, e.g. this or this. Two alternatives exist: Use the after
method, or use threading. I'd like to know more about how the after
method actually works.
More precisely, inspired by this excellent article, where a very high-level description of how the GIL in Python works is given, I'd like to know more how the after
method works in terms of the Python interpreter processing foo
inside tkinter's mainloop
.
I'm particularly confused how the CPython interpreter steps through the code, when I insert code using after
. How is foo
ending up being executed by tkinter's mainloop
?
What I found so far:
Bryan Oakley, quoted from the first link, says: "after does not create another thread of execution. Tkinter is single-threaded. after merely adds a function to a queue."
But inspecting the source code
def after(self, ms, func=None, *args):
"""Call function once after given time.
MS specifies the time in milliseconds. FUNC gives the
function which shall be called. Additional parameters
are given as parameters to the function call. Return
identifier to cancel scheduling with after_cancel."""
if not func:
# I'd rather use time.sleep(ms*0.001)
self.tk.call('after', ms)
else:
def callit():
try:
func(*args)
finally:
try:
self.deletecommand(name)
except TclError:
pass
callit.__name__ = func.__name__
name = self._register(callit)
return self.tk.call('after', ms, name)
doesn't really help me, as it doesn't reveal the answers to these questions, and I'm a novice programmer, so I don't really understand how to trace this further.