tkinter: Passing arguments when binding keys to functions

Martin Franklin mfranklin1 at gatwick.westerngeco.slb.com
Fri Jan 10 10:32:50 CET 2003


On Thu, 2003-01-09 at 21:20, Tim Daneliuk wrote:
> I have an array of 12 items that I want to associate with the 12 Function
> keys.  I want to call a common handler function for all 12 keys and
> initialize the bindings to pass an argument to the handler so it
> can tell who invoked it.  I've tried something like this, but to no
> avail:
> 
> for x in range(len(array)):
> 	y = array[x]	
> 	widget.bind('<F' + str(x+1) + '>', lambda arg=y : CommonHandler(arg))
> 
> Is this general approach valid?
> 
> CommonHandler() in my case, happens to be an already existing routine
> which is just called as CommonHandler(x, default=TRUE).  It, in turn,
> calls os.path.abspath(x).  When this happens, I get the following
> error:
> 
>        AttributeError: Event instance has no attribute '__getitem__'
> 
> This makes me believe that my general approach is correct, but something
> about how I am calling the routine from the binding is different than
> the normal call I make to CommonHandler.
> 
> One other question - is it possible to use the lambda form above to
> pass more than a single argument?
> 
> TIA,
> -- 
> ------------------------------------------------------------------------------
> Tim Daneliuk
> tundra at tundraware.com
> 
> -- 
> http://mail.python.org/mailman/listinfo/python-list


Not sure I can answer your exact questions but here is another way 
to do what (I think...) you want.



from Tkinter import *



class CommonHandler:
    def __init__(self, arg, default=TRUE):
        self.arg = arg
        self.default = default

    def __call__(self, event):
##        os.path.abspath(self.arg)
        print self.arg


#~ now for that loop...

root=Tk()


array = "abcdefg"

for x in range(len(array)):
    y = array[x]
    root.bind("<F%d>" %(x+1), CommonHandler(y))


root.mainloop()










More information about the Python-list mailing list