How to pass an argument to event handler in tkinter?

by elise_daugherty , in category: Third Party Scripts , 25 days ago

How to pass an argument to event handler in tkinter?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by giovanny.lueilwitz , 24 days ago

@elise_daugherty 

In tkinter, you can pass arguments to an event handler by using lambda functions. The lambda function allows you to specify the arguments that you want to pass to the event handler.


Here's an example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
import tkinter as tk

def on_button_click(arg):
    print(arg)

root = tk.Tk()

button = tk.Button(root, text="Click me")
button.pack()

# Passing argument to event handler using lambda function
button.bind("<Button-1>", lambda event, arg="Hello": on_button_click(arg))

root.mainloop()


In this example, we create a button widget and bind the <Button-1> event to a lambda function. We pass the argument "Hello" to the on_button_click event handler using the arg parameter in the lambda function. When you click the button, it will print "Hello" to the console.