Unable to disable menu item wxpython

Viewed 83

I'm working on a test GUI and need to create a popup menu with 2 buttons after clicking on a button. One of the buttons needs to be disabled and will remain disabled. Here is the code I have so far.

class ButtonPopup(wx.Menu):
    def __init__(self, parent):
        wx.Menu.__init__(self)

        item1 = wx.MenuItem(self, wx.ID_ANY, "Item one")
        self.Append(item1)

        item2 = wx.MenuItem(self, wx.ID_ANY, "Item two")
        item2.Enable(enable=False)
        print(str(item2.IsEnabled()))
        self.append(item2)

The second item remains enabled which I can verify with the IsEnabled check and can visually see it enabled. I have tried it as item2.Enable(False) as well and item2.Disable() though MenuItem does not use Disable(). I probably missing a dumb mistake or am approaching the popup menu completely wrong so any help would be great.

Below I put the event function to call the popup in case that helps. But if I left everything enabled everything would be working fine.

def open_popup(self, event):
    self.PopupMenu(ButtonPopup(self), event.GetEventObject().GetScreenPosition())
1 Answers

You have to disable the menuitem after it has been appended to the menu.

See IR05 in the code below:

import wx

class myPanel(wx.Frame):
    def __init__(self, *args, **kwds):
        wx.Frame.__init__(self, *args, **kwds)
        self.panel = wx.Panel(self)
        text = wx.StaticText(self.panel, -1, "Right click on this panel for a popup menu")
        self.Bind(wx.EVT_CONTEXT_MENU, self.ShowPopup)
        self.Show()

    def ShowPopup(self, event):
        popmenu = wx.Menu()
        visible = wx.Menu()
        visible.Append( -1, "VIS04")
        visible.Append( -1, "VIS05")
        visible.Append( -1, "VIS06")
        visible.Append( -1, "VIS07")
        popmenu.Append( -1, "Visible", visible)

        infrared = wx.Menu()
        infrared.Append( -1, "IR04")
        disabled = wx.MenuItem(infrared, -1, "IR05")
        infrared.Append(disabled)
        infrared.Append( -1, "IR06")
        infrared.Append( -1, "IR07")
        popmenu.Append( -1, "Infrared", infrared)

        disabled.Enable(False)

        simulation = wx.Menu()
        simulation.Append( -1, "SIM04")
        simulation.Append( -1, "SIM05")
        simulation.Append( -1, "SIM06")
        simulation.Append( -1, "SIM07")
        popmenu.Append( -1, "Simulation", simulation)

        self.Bind(wx.EVT_MENU, self.OnChoice)
        self.PopupMenu(popmenu)
        popmenu.Destroy()

    def OnChoice(self, event):
        id = event.GetId()
        obj = event.GetEventObject()
        print("Option chosen",obj.GetLabelText(id))

if __name__ == '__main__':
    app = wx.App()
    myPanel(None)
    app.MainLoop()

enter image description here

Related