views:

88

answers:

3

Hi friends.,

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.

thanks in advance

sag

+4  A: 

What about

import functools
def callback(self, event, param):
    pass
arg = 123
widget.bind("", functools.partial(callback, param=arg))
Philipp
giving Exception:leftClickCallback() got an unexpected keyword argument 'param'
sag
Does your callback as the param argument? This works ok form me.
luc
self.l.bind("<Button-1>", functools.partial(self.leftClickCallback,param=fi)) this is the bind step.whats wrong here?
sag
How is the `leftClickCallback` method declared?
Philipp
def leftClickCallback(self,event,param):
sag
A: 

I think that in most cases you don't need any argument to a callback because the callback can be an instance method which can access the instance members:

from Tkinter import *

class MyObj:
    def __init__(self, arg):
        self.arg = arg

    def callback(self, event):
        print self.arg

obj = MyObj('I am Obj')
root = Tk()
btn=Button(root, text="Click")
btn.bind('<Button-1>', obj.callback)
btn.pack()
root.mainloop()

But I think the functools solution proposed by Philipp is also very nice

luc
+3  A: 

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.OnMouseDown(event, arg))

Edit in response to a question in the comments:

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

def OnMouseDown(self, event, arg):
    print arg
Bryan Oakley
then how to access that arg in the event handler? what should be the declaration of the handler
sag
@sag: see my edit. Short answer: you access it like any other argument.
Bryan Oakley
thank you so much Bryan . it is perfect .
sag