How to pass an argument to the event handler in Tkinter?

PythonTkinterServer Side ProgrammingProgramming

In most situations, the callback functions can refer to as an Instance Method. An instance method accesses all its members and performs operations with them without specifying any arguments.

Let's consider a case where more than one component is defined and we want to handle some events with those components. To run multiple events, we prefer to pass multiple arguments in event handlers.


In this example, we have created multiple button widgets in a frame, and we will handle various events by passing the name of the widget as arguments. Once a Button will be clicked, it will update the Label widget and so on.

#Import the Tkinter library
from tkinter import *
from tkinter import ttk
from tkinter import filedialog
#Create an instance of Tkinter frame
win= Tk()
#Define the geometry
#Define Event handlers for different Operations
def event_low(button1):
   label.config(text="This is Lower Value")
def event_mid(button2):
   label.config(text="This is Medium Value")
def event_high(button3):
   label.config(text="This is Highest value")
#Create a Label
label= Label(win, text="",font=('Helvetica 15 underline'))
#Create a frame
frame= Frame(win)
#Create Buttons in the frame
button1= ttk.Button(frame, text="Low", command=lambda:event_low(button1))
button2= ttk.Button(frame, text="Medium",command= lambda:event_mid(button2))
button3= ttk.Button(frame, text="High",command= lambda:event_high(button3))


Running the above code will display a window that contains Buttons Low, Medium, and High. When we click a button, it will show some label text on the window.

Updated on 22-Apr-2021 07:25:27