I want to run a function alongside the main loop of a window. I have this code:
from tkinter import *
window = Tk()
def task():
print("hello")
window.after(1000, task)
window.after(1000, task)
window.mainloop()
This code prints "hello" every second. If i add an argument to the function task
like so:
from tkinter import *
window = Tk()
def task(arg):
print("hello")
window.after(1000, task(0))
window.after(1000, task(0))
window.mainloop()
The function gets executed without any delay until this error message is shown:
RecursionError: maximum recursion depth exceeded while calling a Python object
Is it just not possible to use a callback function with arguments in the after
method?
Weirdly enough, there seems to be no documentation on this method on the official API site.
This happens because task(0) is actually calling itself instead of passing the name of the function to call like in the first code you are passing an expression which calls the function task with 0 as an argument, and when this happens the function calls itself again and again because inside of the function call you are calling it again using the same expression, this happens until the maximum depth is reached in python of recursive calls (I think it is 1000).
A solution to this is to use lambda expression like this if you want to pass an argument:
window.after(1000, lambda:task(0))