Reputation: 2543
Using wxPython, I have a frame setup with a menu and a status bar. The menu is generated from an indented text file, from which I use to create a nice nested menu bar with each menu item bound to a specific function. I have a "Toggle Status Bar" menu check item which is bound OnToggleStatusBar().
I would like to see if the menu item is checked or not and react accordingly, but I cannot seem to access the menuItem from the event. If I use GetId(), how can that be used to find the menu item? I tried event.GetId() with FindWindowById() but got nothing. I also tried event.GetEventObject(), which returned a menu but not a menu item.
def OnToggleStatusBar(self, event):
id = event.GetId()
menu = event.GetEventObject()
menuItem = menu.FindWindowById(id) #does not work
print self.FindByWindowId(id) # prints None
Upvotes: 1
Views: 2175
Reputation: 22443
Use the event to access the data you want.
print event.Id
print event.Selection # returns 1 if checked 0 if not checked
print event.IsChecked() # returns True if checked False if not checked
print out all of the attributes with:
print dir(event)
Upvotes: 0
Reputation: 22688
You don't need to find the item, you can use wxMenuBar::IsChecked()
, which will do it for you, directly. And you can either just store the menu bar in self.menuBar
or retrieve it from the frame using its GetMenuBar()
method.
Upvotes: 2
Reputation: 33071
It's a bit convoluted, but not too bad. Basically you need to use the menu's FindItem
method, which takes the string name of the menu item. This returns its id, which you can then use the menu's FindItemById
method for. Here's a quick and dirty example:
import wx
########################################################################
class MyForm(wx.Frame):
""""""
#----------------------------------------------------------------------
def __init__(self):
"""Constructor"""
wx.Frame.__init__(self, None, title="wx.Menu Tutorial")
self.panel = wx.Panel(self, wx.ID_ANY)
# Create menu bar
menuBar = wx.MenuBar()
# create check menu
checkMenu = wx.Menu()
wgItem = checkMenu.Append(wx.NewId(), "Wells Fargo", "", wx.ITEM_CHECK)
self.Bind(wx.EVT_MENU, self.onFargo, wgItem)
citiItem = checkMenu.Append(wx.NewId(), "Citibank", "", wx.ITEM_CHECK)
geItem = checkMenu.Append(wx.NewId(), "GE Money Bank", "", wx.ITEM_CHECK)
menuBar.Append(checkMenu, "&Check")
# Attach menu bar to frame
self.SetMenuBar(menuBar)
#----------------------------------------------------------------------
def onFargo(self, event):
""""""
menu = event.GetEventObject()
item_id = menu.FindItem("Wells Fargo")
item = menu.FindItemById(item_id)
print item.IsChecked()
#----------------------------------------------------------------------
# Run the program
if __name__ == "__main__":
app = wx.App(False)
frame = MyForm().Show()
app.MainLoop()
Upvotes: 1