Question about Tkinter

Grant Edwards grante at visi.com
Fri Aug 10 12:46:15 EDT 2001


In article <9l07a201rdj at enews4.newsguy.com>, Alex Martelli wrote:
> "Benjamin Wu" <chase at gnuchina.org> wrote in message
>> When I use Tkinter, I met a question as following:
>> I create three buttons and thire callback function
>> is the same, how to know which button active callback
>> function when one of they pressed?
>>
>> Anyone can help me?
> 
> Use different callables for the callbacks -- if it must be
> the same function, curry the function with different
> preset arguments -- see for example
> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52549
> about how to do currying in Python.

A slightly different way is to use lamgda.  It's best for
simple cases where you just want to pass a few arguments that
are calcualted at run-time. Here's an excerpt from an 8-queens
demo program that binds a callback to each button (space on a
chessboard):

     1	        for y in range(size):
     2	            f  = Frame(self.__frame)
     3	            for x in range(size):
     4	                if (x+y) % 2:
     5	                    bg = "#bbb"
     6	                else:
     7	                    bg = "#eee"
     8	                b = Button(f, 
     9	                     bitmap='@%s' % bitmapfile,
    10	                     highlightthickness=0, 
    11	                     relief=FLAT, 
    12	                     background=bg, 
    13	                     activebackground="#fff",
    14	                     foreground=bg)
    15	                b.bind("<Button-1>",lambda event,xx=x,yy=y: board.toggleSpace(xx,yy))
    16	                b.bind("<Any-Enter>", self.__noop)
    17	                b.bind("<Any-Leave>", self.__noop)
    18	                b.bind("ButtonRelease-1>", self.__noop)
    19	                b.pack(side=LEFT)
    20	                self.__button[y][x] = b
    21	            f.pack(side=BOTTOM)


Line 15 is where the interesting bit happens.  

When a <Button-1> is pressed over any of the 64 spaces on the
chessboard, the anonymous function defined by the lamba is
called.  That function receives one parameter called "event"
from Tk, and has two default parameters "xx" and "yy" whose
default values are set when the binding is done.  Since Tk only
passes the single "event" parameter, "xx" and "yy" will have
the values specified by "x" and "y" when the lambda operation
took place.

The anonymous callback function will then call
board.toggleSpace() passing it the index values. The "event"
parameter that is passed to the anonymous callback function is
ignored.

Curry is probably a more readable solution to a non-Schemer.  ;)

-- 
Grant Edwards                   grante             Yow!  Hey!! Let's watch
                                  at               the' ELEVATOR go UP and
                               visi.com            DOWN at th' HILTON HOTEL!!



More information about the Python-list mailing list