<p>它可能不漂亮,但我发现使用一个菜单Id范围的列表是有效的。它不仅易于理解,而且灵活,如:</p>
<pre class="lang-py prettyprint-override"><code>import wx
class MenuCallback(wx.Frame):
def __init__(self, *args, **kwds):
self.frame=wx.Frame.__init__(self, *args, **kwds)
self.menubar = wx.MenuBar()
menu1 = wx.Menu()
menu_item_1 = menu1.Append(wx.ID_OPEN, "&File")
menu_item_2 = menu1.Append(wx.ID_EXIT, "&Exit...")
#Build a list of things via another function or just a declaration
self.list_of_things = ["Thing No 1", "Thing No 2", "Thing No 3"]
list_used = wx.Menu()
thing_count = 101
for thing in self.list_of_things:
t1 = wx.MenuItem(list_used, thing_count, thing)
list_used.AppendItem(t1)
thing_count +=1
thing_end = wx.MenuItem(list_used,199,'End of List')
list_used.AppendItem(thing_end)
menu1.AppendMenu(wx.ID_FILE,'&Things',list_used)
self.menubar.Append(menu1, "&File")
self.SetMenuBar(self.menubar)
# Create bindings for the Thing list
i_count = 101
for i in self.list_of_things:
self.Bind(wx.EVT_MENU, self.OnThingOpen, id=i_count)
i_count = i_count + 1
self.Bind(wx.EVT_MENU, self.OnThingEnd, id=199)
self.Bind(wx.EVT_MENU, self.OnClose, id=wx.ID_EXIT)
self.Show(True)
def OnThingOpen(self, event):
id_index = 101
id_selected = event.GetId()
id_selected = id_selected - id_index
print "Option =", id_selected
print "Thing selected =", str(self.list_of_things[id_selected])
def OnThingEnd(self, event):
id_selected = event.GetId()
print "Option =", id_selected
def OnClose(self, event):
self.Close()
if __name__ == '__main__':
app = wx.App()
MC=MenuCallback(parent=None, id=-1)
app.MainLoop()
</code></pre>