[Tutor] parameter passing
alan.gauld@bt.com
alan.gauld@bt.com
Mon, 21 Oct 2002 11:46:18 +0100
> Lucky for me, he had a great example of how it can be done,
> and I am posting the answer because I think the knowledge
> is worthwhile
> Incorrect -
>
> Button(self,text='name',command=self.update_name([input1]).pac
> k(side=LEFT)
>
> Correct -
> action = lambda x=[input1]:self.update_name(x)
> Button(self,text='name',command=action).pack(side=LEFT)
But note one caveat. If input1 changes between the time
you define the Button(or more accurately the lambda)
and the time you press the button the new input1 will
be ignored! (This is because default arguments in
Python are stored at the time of definition, not at
the time of use)
If you want to use the current value of input1 each time
the command is called you must store it as an instance
variable and access it that way - as Magnus originally
stated.
Also note that the lambda format is not necessary
(as someone showed last week you can use a command
pattern) since you can just define a short function:
def button_callback(self,inp = input1):
return self.update_name(inp)
Button(self,command=self.button_callback).pack()
Alan g.
Author of the 'Learning to Program' web site
http://www.freenetpages.co.uk/hp/alan.gauld