Skip to content
Advertisement

How do I make menu options do different things in WxPython?

I have a problem with my menu in WxPython! In the file header I have ‘File’ and in that I have 2 options, ‘Save’ and ‘Close’…When I click save, I want it to print “Saved” and when I clock quit, the application should print “Closed” and close…But if I click even save it’s closing! So can you please help me. Here is a part of my code:

menubar = wx.MenuBar()
fileMenu = wx.Menu()

menubar.Append ( fileMenu, '&File' )

m1 = fileMenu.Append ( wx.ID_EXIT, 'Save' )
self.Bind ( wx.EVT_MENU, self.OnSave, m1 )

m2 = fileMenu.Append ( wx.ID_EXIT, 'Quit' )
self.Bind ( wx.EVT_MENU, self.OnQuit, m2 )

self.SetMenuBar ( menubar )

And the functions:

def OnSave ( self, event ):
    
    text = self.text_ctrl.GetValue()
    
    fil.write ( text )
    print ( "Saved file")

def OnQuit ( self, event ):
    
    print ( "Closed" )
    self.Close()

Advertisement

Answer

The first parameter of fileMenu.Append is important. It is used to tell one menu item from the other one, but you used the same value for both.

    m1 = fileMenu.Append(wx.ID_SAVE, 'Save')
    self.Bind(wx.EVT_MENU, self.OnSave, m1)
    
    m2 = fileMenu.Append(wx.ID_EXIT, 'Quit')
    self.Bind(wx.EVT_MENU, self.OnQuit, m2)

In my programs I prefer getting a free id from system, using wx.NewId(). If you have these “stock” menu entries, ID_SAVE and ID_EXIT make perfect sense, but if you make your own entries, you can do:

    m3 = fileMenu.Append(wx.NewId(), 'My own menu item')
    self.Bind(wx.EVT_MENU, self.OnMyOwnFunction, m3)
    m4 = fileMenu.Append (wx.NewId(), 'Another menu item')
    self.Bind(wx.EVT_MENU, self.OnAnotherFunction, m4)
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement