Peter Horne
Peter Horne

Reputation: 6856

Bind event to wx.Menu() instead of to the menu item in wxPython

My problem can be easily defined with the following code:

self.Bind(wx.EVT_MENU_OPEN, self.OnAbout)

This will mean that when I click on any wx.Menu() in the MenuBar, the function 'onAbout()' is called. How do I bind this event to a specific wx.Menu() which is called wx.MenuAbout() ?

If you are feeling extra helpful, perhaps you could provide me with a link to the documentation for event handlers. I could find documentation for the event handler function but not for the actual event handlers (such as wx.EVT_MENU).

Similar question but I am not looking to bind a range of wx.Menu()'s to the event: Is it possible to bind an event against a menu instead of a menu item in wxPython?

Edit: Ideally, this is what I'd like to be able to do:

menuAbout = wx.Menu()
self.Bind(wx.EVT_MENU, self.OnAbout, id=menuAbout.GetId())

The result would be that any other items in the .menuBar() (such as: File, Edit, Tools) work as normal menu's, but 'About' works like a clickable link.

Using the wx.EVT_MENU_OPEN means that the File menu can be opened, then when the mouse hovers over 'about', the self.OnAbout function get's called which I only what to happen when the user clicks specifically on the 'About' menu.

Upvotes: 1

Views: 5696

Answers (2)

nmz787
nmz787

Reputation: 2180

This works for me:

class myFrame(wx.Frame):
    def __init__(self):
        wx.Frame.__init__(self, None, -1, "my frame")

        #give the Frame a menu bar
        self.frame_menubar = wx.MenuBar()

        fileMenu = wx.Menu()
        self.frame_menubar.Append(fileMenu, "File")

        self.rotMenu = wx.Menu()
        self.frame_menubar.Append(self.rotMenu, "Rotate")

        self.SetMenuBar(self.frame_menubar)

        self.Bind(wx.EVT_MENU_OPEN, self.rot)

    def rot(self, event):
        if event.GetMenu() == self.rotMenu:
            print 'rotate clicked'

Upvotes: 0

Mathieu
Mathieu

Reputation: 7581

Why don't you just bind to the menu items using EVT_MENU instead?

EVT_MENU_OPEN will fire as soon as any menu is opened. That being said, if that's what you really want, you can always do this:

Where you define your menu:

self.about_menu = wx.Menu()  # or whatever inherited class you have
self.Bind(wx.EVT_MENU_OPEN, self.on_menu_open)

Then your callback:

def on_menu_open(self, event):
    if event.GetMenu()==self.about_menu:
         #do something

Upvotes: 5

Related Questions