How to pass an argument to event handler in tkinter? How to pass an argument to event handler in tkinter? tkinter tkinter

How to pass an argument to event handler in tkinter?


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)


What about

import functoolsdef callback(self, event, param):    passarg = 123widget.bind("", functools.partial(callback, param=arg))


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.argobj = 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