Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass an argument to event handler in tkinter?

widget.bind('<Button-1>',callback)   # binding   def callback(self,event)     #do something 

I need to pass an argument to callback() . The argument is a dictionary object.

like image 709
sag Avatar asked Jul 21 '10 06:07

sag


People also ask

Can you pass arguments to event handler?

If you want to pass a parameter to the click event handler you need to make use of the arrow function or bind the function. If you pass the argument directly the onClick function would be called automatically even before pressing the button.

How do I bind the Enter key to a function in Tkinter?

To bind the <Enter> key with an event in Tkinter window, we can use bind('<Return>', callback) by specifying the key and the callback function as the arguments. Once we bind the key to an event, we can get full control over the events.

What is Tkinter event handler?

Python Tkinter event handler It is simply an action like clicking on a button that leads to another event. Code: In the following code, we define a class in which we created an object. We added an event handler on a button which is actions to quit a window. It Handles the input received in an event.

Which method is used to associate a Tkinter mouse event with its event handler?

Use the bind() method to bind an event to a widget. Tkinter supports both instance-level and class-level bindings.


2 Answers

You can use lambda to define an anonymous function, such as:

data={"one": 1, "two": 2}  widget.bind("<ButtonPress-1>", lambda event, arg=data: self.on_mouse_down(event, arg)) 

Note that the arg passed in becomes just a normal argument that you use just like all other arguments:

def on_mouse_down(self, event, arg):     print(arg) 
like image 132
Bryan Oakley Avatar answered Sep 19 '22 13:09

Bryan Oakley


What about

import functools def callback(self, event, param):     pass arg = 123 widget.bind("", functools.partial(callback, param=arg)) 
like image 36
Philipp Avatar answered Sep 17 '22 13:09

Philipp