How can I pass arguments to Tkinter button's callback command?

TkinterServer Side ProgrammingProgramming

Tkinter Buttons are used for handling certain operations in the application. In order to handle such events, we generally pass the defined function name as the value in the callback command. For a particular event, we can also pass the argument to the function in the button’s command.

There are two ways to pass the argument to the tkinter button command −

  • Using Lambda or anonymous function
  • Using Partials


In this example, we will create a simple application that will contain a text label and a button to change the value of label text. We will pass the label as the argument in the button command by using lambda function.

#Import necessary Library
from tkinter import *
from tkinter import ttk
#Create an instance of tkinter window
win= Tk()
#Set the geometry of tkinter window
#Define the function to change the value in label widget
def change_text(label):
   label.configure(text= "Hey, I am Label-2", background="gray91")
#Create a Label
label = Label(win, text= "Hey, I am Label-1", font= ('Helvetica 15 underline'), background="gray76")
#Create a button
btn= ttk.Button(win, text= "Change", command= lambda:change_text(label))


Running the above code will display a window which contains a text label and a button to change the value of the label.

Now click on “Change” button to change the value of the label widget.

Published on 15-Apr-2021 13:37:09