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:
JavaScript
x
13
13
1
menubar = wx.MenuBar()
2
fileMenu = wx.Menu()
3
4
menubar.Append ( fileMenu, '&File' )
5
6
m1 = fileMenu.Append ( wx.ID_EXIT, 'Save' )
7
self.Bind ( wx.EVT_MENU, self.OnSave, m1 )
8
9
m2 = fileMenu.Append ( wx.ID_EXIT, 'Quit' )
10
self.Bind ( wx.EVT_MENU, self.OnQuit, m2 )
11
12
self.SetMenuBar ( menubar )
13
And the functions:
JavaScript
1
12
12
1
def OnSave ( self, event ):
2
3
text = self.text_ctrl.GetValue()
4
5
fil.write ( text )
6
print ( "Saved file")
7
8
def OnQuit ( self, event ):
9
10
print ( "Closed" )
11
self.Close()
12
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.
JavaScript
1
6
1
m1 = fileMenu.Append(wx.ID_SAVE, 'Save')
2
self.Bind(wx.EVT_MENU, self.OnSave, m1)
3
4
m2 = fileMenu.Append(wx.ID_EXIT, 'Quit')
5
self.Bind(wx.EVT_MENU, self.OnQuit, m2)
6
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:
JavaScript
1
5
1
m3 = fileMenu.Append(wx.NewId(), 'My own menu item')
2
self.Bind(wx.EVT_MENU, self.OnMyOwnFunction, m3)
3
m4 = fileMenu.Append (wx.NewId(), 'Another menu item')
4
self.Bind(wx.EVT_MENU, self.OnAnotherFunction, m4)
5