Tkinter Callback question

Martin Franklin mfranklin1 at gatwick.westerngeco.slb.com
Tue Aug 13 04:56:23 EDT 2002


On Monday 12 Aug 2002 8:04 pm, Jack B. wrote:
> Perhaps someone can help me with the proper syntax using the
> "command=" option while making a menu button.  Here's what I want to
> do:
>
> for number in range(-4,1):
>   temp = get_dates.dbdate(number)
>   date_menu.add_command(label=temp, command=self.set_valid_date(temp)
> menubar.add_cascade(label="Choose Date", menu=date_menu)
>
> (get_dates.dbdate will return a correctly formatted date, given number
> of days back or forward.  set_valid_date will set act on the date
> passed)
>
> This code will list dates from today back 4 days but I can't seem to
> call the "command" part and pass any data.  The command executes
> immediatly, and the buttons created do nothing.  Surely there is a way
> to do this?  The only way I can execute a command is by NOT passing
> any data, ie.. command=self.hello.
>
> rb



There are two schools of thought on this one.  The first uses lambda

so this:-

date_menu.add_command(label=temp, command=self.set_valid_date(temp))

becomes:-

date_menu.add_command(label=temp, command=lambda self=self, 
    temp=temp :  self.set_valid_date(temp))


The second (and IMHO) the better uses a class with a __call__ method defined:-


class MenuCallback:
    def __init__(self, temp):
        self.temp=temp
    
    def __call__(self):
        ## do somthing with self.temp
        print self.temp

#so this:-
date_menu.add_command(label=temp, command=self.set_valid_date(temp))

becomes this:-

date_menu.add_command(label=temp, command=MenuCallback(temp))


HTH,
Martin.














More information about the Python-list mailing list