3

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

3 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

That is perfect! I need to learn the terminology better so its easier to find the answers via search, thank you for taking the time to help me!
2

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()

Comments

1

I have tried. It works!

self.Bind(wx.EVT_BUTTON, lamdba evt, a=1, b=2: self.funcName(evt, a, b), buttonName)

So, you can pass any data to any function.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.