[Tutor] Shortening the code.

Alan Gauld alan.gauld at btinternet.com
Fri Nov 25 22:24:59 CET 2011


On 25/11/11 17:11, Mic wrote:

>> for making a function that calls another function with a fixed
>> argument is
>
> command = lambda button=button: button_clicked(button)
>
> Alright! What is a fixed argument?


Its onre that is the same every time the function is called.

The lambda  construct above is equivalent to the following which may 
make it clearer:

def button_clicked(aButton):
      # do something with aButton here
      # that  uses a lot of code and
      # we want to reuse for any button

Now we want to use that function as an event handler, but the function 
passed as the command in tkinter is not allowed to take an argument.

So we create a very short function that takes no arguments but calls 
button_clicked with a fixed argument. And we do this for two buttons
so that they can both use the button_clicked

def button1_clicked():
     button_clicked(buttonOne)

def button2_clicked():
     button_clicked(buttonTwo)

and we can use these whehn creating our buttons:

buttonOne = Button(parent, command=button1_clicked, ....)
buttonTwo = Button(parent, command=button2_clicked, ....)

Now a shorter way of doing that, which avoids writing lots of these very 
small functions is to use lambda, which is an operator that returns a 
function as a value.

Thus

def add2(x): return x+2

can be written

add2 = lambda x: x+2

And if we don't really care about the name - which is
true for the button commands we can put lambda directly
into the widget creation:

buttonOne = Button(parent,
                    command=lambda b=buttonOne: button_clicked(b), ....)

buttonTwo = Button(parent,
                    command=lambda b=buttonTwo: button_clicked(b), ....)

Note that this works because the lambda defines a default argument for 
the command. Thus Tkinter can call the function with no arguments and 
Python will insert the default value at runtime.

HTH,

Alan G.




More information about the Tutor mailing list