[Tutor] Multiple buttons, One callback

Alan G alan.gauld at freenet.co.uk
Sat Sep 17 01:31:35 CEST 2005


> I've always been about to bind each button to one callback function 
> which could then determine which button was clicked, and from that 
> data grab the necessary data and perfrom the operations on that 
> data.

There are several ways to do this.
The most direct is to use bind which passes an event object to the
callback. By interroghating the event you can determine its source.

The other way that i tend to use is:

def commonCallback(source):
    if source == 'A': doButtonA()
    elif source == 'B' : doButtonB()
    etc...

A = Button(parent, text='A', lambda id='A': commonCallback(id))
B = Button(parent, text='B', lambda id='B': commonCallback(id))

THat is create a common function that takes the source identifier
as a parameter. For each widget callback use a lambda to create
an anonymous handler that calls the comon function passing the
source id as an argument. The source Id is set up as a default
parameter value in the lambda definition.

HTH,

Alan G
Author of the Learn to Program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld 



More information about the Tutor mailing list