Search code examples
pythonwxpythonampersand

App doesn't put Ampersands in Menu Items (wxPython)


The problem is simple but i still coudn't figure it out, when i run the code, the Ampersands don't appear in Menu Items. Why?! I'm using Python 3.7.7 and wxPython 4.1.0, on Thonny v3.2.7.

import wx

def OnQuit(e):
    frame.Close()

app = wx.App()

frame = wx.Frame(None, -1, "wxPython Menu")
frame.SetSize(400, 300)

submenu1 = wx.Menu()
submenu1.Append(121, "Import Newsfeed List")
submenu1.Append(122, "Import Bookmarks")
submenu1.Append(123, "Import Mail")

menu1 = wx.Menu()
menu1.Append(10, "Open")
menu1.Append(11, "Save")
menu1.AppendSeparator()
menu1.AppendSubMenu(submenu1, "Import")
menu1.Append(13, "No Exit")

menu2 = wx.Menu()
menu2.Append(20, "Cut")
menu2.Append(21, "Copy")
menu2.Append(22, "Paste")
menu2.Enable(20, False)

menu3 = wx.Menu()
item = wx.MenuItem(menu3, 30, "&Quit\tCtrl+Q")
item.SetBitmap(wx.Bitmap("quit.png"))
menu3.Append(item)
menu3.Bind(wx.EVT_MENU, OnQuit, id = 30)

menuBar = wx.MenuBar()
menuBar.Append(menu1, "&File")
menuBar.Append(menu2, "&Edit")
menuBar.Append(menu3, "&Extras")

frame.SetMenuBar(menuBar)
frame.Centre()
frame.Show()

app.MainLoop()

Solution

  • SetItemLabel(self, label)
    Sets the label associated with the menu item.

    Note that if the ID of this menu item corresponds to a stock ID, then it is not necessary to specify a label: wxWidgets will automatically use the stock item > label associated with that ID. See the constructor for more info.

    The label string for the normal menu items (not separators) may include the
    accelerator which can be used to activate the menu item from keyboard. An accelerator key can be specified using the ampersand & character. In order to embed an ampersand character in the menu item text, the ampersand must be doubled. ** https://docs.wxpython.org/wx.MenuItem.html#wx-menuitem

    The ampersand (&) is traditionally used as an accelerator on menu items.
    If you press the ALT button your menus will (if defined with accelerators i.e. &File where the & next to F means pressing F will open the File menu) display with the accelerator letter underlined.
    Press F and the File menu opens.
    If menu items in the File menu have accelerators, they too will have a letter underlined, pressing that letter will select that menu item.

    If you require an actual ampersand (&) without special meaning e.g. Close & Quit, you need to double the ampersand i.e. the items label should created as Close && Quit or &Close && Quit if the menu should not only display as Close & Quit but also respond when the user presses the letter C.