How do I enable or disable a menu item

Similar to other widgets, menus and menu items can be enabled or disabled. A disabled menu or menu item usually displays as gray text, rather than black. A disabled menu or menu item does not trigger highlight or selection events, it's invisible to the event system.

Listing 10.5 displays sample code that toggles a menu item's enabled state, using the menu bar IsEnabled() and Enable() methods inside the button event handler.

Listing 10.5 Sample enable and disable item code import wx

class MyFrame(wx.Frame):

"Enable/Disable Menu Example")

self.btn = wx.Button(p, -1, "Disable Item", (20,20)) self.Bind(wx.EVT_BUTTON, self.OnToggleItem, self.btn)

menu.Append(ID_SIMPLE, "Simple menu item") self.Bind(wx.EVT_MENU, self.OnSimple, id=ID_SIMPLE)

menu.AppendSeparator() menu.Append(wx.ID_EXIT, "Exit")

self.Bind(wx.EVT_MENU, self.OnExit, id=wx.ID_EXIT)

menuBar = wx.MenuBar() menuBar.Append(menu, "Menu") self.SetMenuBar(menuBar)

def OnSimple(self, event):

wx.MessageBox("You selected the simple menu item")

def OnExit(self, event): self.Close()

def OnToggleItem(self, event): menubar = self.GetMenuBar() enabled = menubar.IsEnabled(ID_SIMPLE) menubar.Enable(ID_SIMPLE, not enabled) self.btn.SetLabel(

(enabled and "Enable" or "Disable") + " Item")

if _name_ == "_main app = wx.PySimpleApp() frame = MyFrame() frame.Show() app.MainLoop()

To view or change the enable state of a menu item from the menu bar, from a specific menu, or from the menu item itself, call wx.MenuBar.IsEnabled(id), wx.Menu.IsEnabled(id), or wx.MenuItem.IsEnabled(). Menu bar and menu methods each take the wxPython identifier of a menu item. Both methods return True if the item exists and is enabled, and False if the item is disabled or does not exist. The only difference is that the wx.Menu method only searches within that particular menu, while the menu bar method searches the entire menu bar. The wx.MenuItem method takes no arguments, and returns the state of that particular menu item.

To change the enabled state, use wx.MenuBar.Enable(id, enable), wx.Menu. Enable(id, enable), or wx.MenuItem.Enable(enable). The enable parameter is a Boolean. If True, the menu item in question is enabled, if False, it is disabled. The scope of the Enable() methods is the same as the IsEnabled() methods. You can also enable or disable an entire top-level menu using the method wx.MenuBar. EnableTop(pos, enable). In this case, the pos parameter is the integer position of the menu within the menu bar, and the enable parameter is a Boolean.

Was this article helpful?

+1 -5

Post a comment