Passing arguments to callbacks

If a callback does not take any argument, it can be handled with a simple function, such as the one shown in the preceding code. However, if a callback needs to take arguments, we can use the lambda function, as shown in the following code snippet:

def my_callback (argument)   #do something with argument

Then, somewhere else in the code, we define a button with a command callback that takes some arguments, as follows:

tk.Button(root,text="Click", command=lambda: my_callback ('some argument'))

Python borrows a specific syntax from functional programming, called the lambda function. The lambda function lets you define a single-line, nameless function on the fly.

The format for using lambda is as follows:

lambda ...

Get Tkinter GUI Application Development Blueprints - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.