newbie: callback functions

Remco Gerlich scarblac at pino.selwerd.nl
Tue Apr 17 15:47:20 EDT 2001


koenig at v-i-t.de <koenig at v-i-t.de> wrote in comp.lang.python:
> i meant something like this
>  Button( dlgframe, text="OK", relief=GROOVE, command=load )
> 
> i want to pass "load" pass a eg. filename, so that "load" knows what to load.
> how is this possible?

load gets its argument from Tk, which doesn't know about your filename. So
the only argument it's going to give is the current event (actually, if you
give the function like that, with command=, it gives no arguments at all, I
think.)

What you do is make a new function that calls load with the filename. 
Then you give that function to the Button.

For instance, with a lambda (nameless function), if you have the filename
in the variable 'filename':
Button(dlgframe, text="OK", relief=GROOVE, 
       command = (lambda fn=filename: load(fn)))

Or without the lambda:
def wrapper(fn=filename):
   load(fn)
Button(dlgframe, text="OK", relief=GROOVE, command=wrapper)

You have to give the filename to the lambda as a default
argument, since it can't see variables outside its definition. From 2.1 on
there are nested scopes and that ugliness will be fixed.

-- 
Remco Gerlich



More information about the Python-list mailing list