Tkinter button commands with lambda in Python


Lamda Functions (also referred to as Anonymous Function in Python) are very useful in building Tkinter GUI applications. They allow us to send multiple data through the callback function. Lambda can be inside any function that works as an anonymous function for expressions. In Button Command, lambda is used to pass the data to a callback function.

Example

In this example, we will create an application that will have some buttons in it. The button command is defined with the lambda function to pass the specific value to a callback function.

#Import the library
from tkinter import *
from tkinter import ttk

#Create an instance of Tkinter frame
win= Tk()

#Set the window geometry
win.geometry("750x250")

#Display a Label
def print_text(text):
   Label(win, text=text,font=('Helvetica 13 bold')).pack()

btn1= ttk.Button(win, text="Button1" ,command= lambda:
print_text("Button 1"))
btn1.pack(pady=10)
btn2= ttk.Button(win, text="Button2" ,command= lambda:
print_text("Button 2"))
btn2.pack(pady=10)
btn3= ttk.Button(win, text="Button3" ,command= lambda:
print_text("Button 3"))
btn3.pack(pady=10)

win.mainloop()

Output

Running the above code will display a window that contains some buttons. Each button passing a text message as the argument to a common callback function using lambda function.

Now, click each Button to display the message on the screen.

Updated on: 03-May-2021

22K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements