wxPython: generating event IDs?

Peter Hansen peter at engcorp.com
Sun Mar 10 01:51:31 EST 2002


Grant Edwards wrote:
> 
> I'm trying to figure out a simple way to attach commands to
> buttons in wxPython.  The standard method seems to be
> 
>  1) Define a unique ID number
>  2) Assign that ID number to the button
>  3) Hook a closure to that ID number with EVT_XXXX()
> 
> There must be a way to eliminate the need to predefine unique
> ID numbers.  I hate trying to maintain lists of numbers like
> that (well, more accurately, I'm just bad at it).
> 
> I thought about using the id() of the button, but you don't
> know that until after the button is created, and you need to
> pass the ID in when the button is created.
> 
> There must be a simple solution that I've overlooked...

This little method which I've used inside a wxFrame subclass
demonstrates a slightly simpler approach than "define a unique
ID number".  Note the use of wxNewId() to make that part
trivial.  If you attach your commands to buttons using a 
method you can wrap the little bit of ugliness and never have
to see it again:

    # define menus
    def setupMenus(self, menuList):
        self.mainmenu = wxMenuBar()
        for menuName, menuItems in menuList:
            _menu = wxMenu()
            _menuId = wxNewId()

            for itemName, itemHint, itemMethod in menuItems:
                if itemName == '---':
                    _menu.AppendSeparator()
                elif type(itemName) == type(''):
                    _itemId = wxNewId()
                    _menu.Append(_itemId, itemName, itemHint)
                    EVT_MENU(self, _itemId, getattr(self, itemMethod, self.menuIgnore))

            self.mainmenu.Append(_menu, menuName)

        self.SetMenuBar(self.mainmenu)

        return



More information about the Python-list mailing list