Two Tkinter questions (long)

Grant Edwards nobody at nowhere.nohow
Wed Jul 5 22:01:55 EDT 2000


On Wed, 05 Jul 2000 23:06:17 GMT, Tim Hochberg <tim.hochberg at ieee.org> wrote:

>> Functions bound to events need to take an event as a parameter
>> (if you don't want the event, you can use lambda to discard it):
>>
>> self.filter_entry.bin('<Return>', labda event: self.do_filter())
>
>You still needs to bind self to a default variable in order for it to be
>accesible inside the lambda, e.g,
>
>self.filter_entry.bin('<Return>', lambda event, self=self :
>self.do_filter())

Oops.

The example I had in front of me at the time was binding a
method bound to a global object.  

Any non-global values that are referenced inside the lamba
expression have to be passed in as default valued parameters.

This seems a bit obtuse at first, but it's an extremely handy
thing to know.

A common example of this is creating command functions on the
fly for a bunch of buttons -- something like this snippet which
fills with buttons a "matrix" that represents a chessboard.

For each of the buttons, I want board.toggleSpace() called with
the coordinates of the particular button [some details in the
code have been elided]:

    for y in range(size):
        for x in range(size):
            b = Button(f,bitmap='@%s' % bitmapfile, [...])
	    b.bind("<Button-1>",lambda event,xx=x,yy=y: board.toggleSpace(xx,yy))

In this examle, "board" is a global object, so it can be
referenced directly, but the values for x and y have to be
passed in as default values for parameters, otherwise "x" and
"y" will be evaluated when the button is pressed (and it will
be an error since they won't be around).

What I want is for "x" and "y" to be evaluated at the time the
"bind" method is called, and their values "frozen" and passed
to toggleSpace() later.  Hence the old "default-valued-parameterized-labmda" 
trick.

It will start to make sense after you've used it three or four
times...

-- 
Grant Edwards                   grante             Yow!  Are you selling NYLON
                                  at               OIL WELLS?? If so, we can
                               visi.com            use TWO DOZEN!!



More information about the Python-list mailing list