commands in tkinter when to use lambda and callbacks commands in tkinter when to use lambda and callbacks tkinter tkinter

commands in tkinter when to use lambda and callbacks


command=self.red binds the function to that widget. command=self.red() binds the return value of that function to that widget. You don't want your widget trying to call, say, a number or a string - you want it to call a function. If you want the widget to call a function with an argument, then you would use a lambda:

command=lambda x=None: print('hello world')


A good way to look at it is to imagine the button or binding asking you the question "what command should I call when the button is clicked?". If you give it something like self.red(), you aren't telling it what command to run, you're actually running the command. Instead, you have to give it the name (or more accurately, a reference) of a function.

I recommend this rule of thumb: never use lambda. Like all good rules of thumb, it only applies for as long as you have to ask the question. Once you understand why you should avoid lambda, it's OK to use it whenever it makes sense.