I'm having trouble finding the answer to this to know if its possible. Ive looked in the wxpython demo and done some googling to no avail.
how do I pass some sort of data to the function call when I am binding actions?
for example
self.Bind(wx.EVT_MENU, self.DoThis, item1)
self.Bind(wx.EVT_MENU, self.DoThis, item2)
I have a set of menu options that I want to be handled by the same function (DoThis), but need to pass that function some data because its output depends on which menu item was selected.
I know I can just bind each menu item to a different function so could just replicate it a bunch of times, but for the sake of clarity and length of code, it would be much simpler to handle it all in the same function, because I have about a dozen menu items. Is this even possible? Thanks
a related question is Is it possible to pass arguments into event bindings?. This can do it by passing arguments to callback, as you can see to passing arguments to callbacks.
You could do it like this.
import wx
class TestFrame(wx.Frame):
def __init__(self, *args, **kwargs):
super(TestFrame, self).__init__(*args, **kwargs)
menubar = wx.MenuBar()
self.SetMenuBar(menubar)
menuFile = wx.Menu()
self.menuSave = menuFile.Append(-1, 'Save', 'Save Document')
self.menuClose = menuFile.Append(-1, 'Close', 'Close Application')
menubar.Append(menuFile, '&File')
self.Bind(wx.EVT_MENU, self.onMenu)
panel = wx.Panel(self)
pSizer = wx.BoxSizer(wx.VERTICAL)
panel.SetSizer(pSizer)
vSizer = wx.BoxSizer(wx.VERTICAL)
vSizer.Add(panel, 1, wx.EXPAND)
self.SetSizer(vSizer)
self.Layout()
def onMenu(self, event):
menuId = event.Id
if menuId == self.menuSave.Id:
print 'menuSave'
elif menuId == self.menuClose.Id:
print 'menuClose'
if __name__ == '__main__':
wxapp = wx.App(False)
testFrame = TestFrame(None)
testFrame.Show()
wxapp.MainLoop()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With