menu.add_command options

Gustavo Cordova gcordova at hebmex.com
Wed Mar 27 10:57:20 EST 2002


> 
> Tkinter:
> In the line:
> 
> file_menu.add_command(label='Load Form', underline=0,
> command=self.open_file)
> 
> Does anyone have a list of options that go with the 
> menu.add_command?  I
> need to pass the frame to the method open_file, but I don't 
> know how to
> pass that as an argument.  The book I have Python and Tkinter
> programming just says "options..."  While I am all for a good mystery,
> it is somewhat disheartening to find in a $50+ book.  
> 

Ahhh, Ye Eternal Callback Questions....

:-)

THE most flexible solution I've ever used, involves
using a callback class, where there's a __call__ method
defined. That way, you create objects which can be
called, just like functions.

The nices part is that objects can carry around stuff
which you can later apply during that invocation of
the __call__ method.

A simple class like this is enough for your purposes (maybe):

class Callback:
    def __init__(self, function, *args, **kwargs):
        self.default_args = args
        self.default_kwargs = kwargs
        self.function = function
    def __call__(self, *more_args, **more_kwargs):
        # Create an updated argument tuple and kw-args dictionary.
        more_args = self.default_args + more_args
        more_kwargs.update(self.default_kwargs)

        # And call the function with all this stuff.
        self.function(*more_args, **more_kwargs)

        # If you're not using 2.x, then:
        # apply(self.function, more_args, more_kwargs)

So now, you can:

file_menu.add_command(label='Load Form',
                      underline=0,
                      command=Callback(self.open_file, FrameName, etc))

When the menu is invoked, the __call__ method of the object
you passed as argument for "command=" above is called,
which does the little mambo of calling the function you defined,
with the default parameters you defined.

Nice, eh?

-gustavo




More information about the Python-list mailing list