The code below does not work - no matter which item in a menu is clicked, it will always print “4”, i.e. the last value in the list. Obviously I am missing something essential about the behavior of lambda and how it can properly be used to handle events. I use it for this purpose elsewhere without trouble, but I am always using static values, never iterating through an anonymous list like this. I would like to avoid clumsy workarounds if possible (I was having other, unrelated problems with my initial solution), but I’m also just curious why this fails.
thanks,
Nat
···
import wx
def menu_handler (i) :
print i
class MyFrame(wx.Frame):
def init (self, *args, **kwds) :
wx.Frame.init(self, *args, **kwds)
panel = wx.Panel(self, -1, size=(600,480))
btn = wx.Button(panel, -1, “Click me!”, pos=(240,200))
self.Bind(wx.EVT_BUTTON, self.OnClick, btn)
def OnClick (self, event) :
btn = event.GetEventObject()
menu = wx.Menu()
for i in range(5) :
item = menu.Append(-1, “print %d” % i)
self.Bind(wx.EVT_MENU, lambda evt: menu_handler(i), item)
btn.PopupMenu(menu)
menu.Destroy()
if name == “main” :
app = wx.App(0)
frame = MyFrame(None, -1, “Test”)
frame.Fit()
frame.Show()
app.MainLoop()