1

How can I give a variable to a function when I bind something? As a simple example:

def test(self):
    self.MyTextCtrl.Bind(wx.EVT_TEXT, self.something, AnyVariable)

def something(self, event, x)
    # do something
    print x

As you see, I want to give the value "AnyVariable" to the function "something" so that it will be used as the "x". How can I do this? This example doesn't work.

Edit: @ Paul McNett: Yeah, what I'm trying to do is more like:

def test(self):
    self.MyTextCtrl1.Bind(wx.EVT_TEXT, self.something, Variable1)
    self.MyTextCtrl2.Bind(wx.EVT_TEXT, self.something, Variable2)
    self.MyTextCtrl3.Bind(wx.EVT_TEXT, self.something, Variable3)

def something(self, event, x)
    # do something by including x

x=Variable1 when "MyTextCtrl1" is edited, x=Variable2 when "MyTextCtrl2" is edited and x=Variable3 when "MyTextCtrl3" is edited.

Of course I also could write 3 different functions ("def something1", "def something2", "def something3") and bind them to "MyTextCtrl1", "MyTextCtrl2" or "MyTextCtrl3". But I thought it could be much easier when I use this variable instead ;)

Munchkin
  • 4,528
  • 7
  • 45
  • 93

1 Answers1

1

One of the following approaches should do it:

  • Introduce a global variable (variable declaration outside the function scope at module level).

    x = None
    def test(self):
        self.MyTextCtrl.Bind(wx.EVT_TEXT, self.something)
    
    def something(self, event):
        global x
        x = ... # alter variable on event
    
  • Introduce a member variable of a class.

  • Furthermore wx.EVTHandler suggests anything as event handler that is callable. For this case I've written a simple class to hold one value (extendable for multiple values) and that implements a __call__ method. Interfering special methods is an advanced topic, for this case I've put together example code:

    import wx
    
    class TestFrame(wx.Frame):
        def __init__(self, *args, **kwargs):
            wx.Frame.__init__(self, None, -1, *args, **kwargs)
            sizer = wx.BoxSizer(wx.VERTICAL)
            self.SetSizer(sizer)
            b = wx.Button(self, -1, "Test")
            sizer.Add(b)
            b.Bind(wx.EVT_BUTTON, TestHandler("foo"))
            self.Show()
    
    class TestHandler:
        def __init__(self, value):
            self.value = value
    
        def __call__(self, event):
            print event
            print "My value is:", self.value
    
    if __name__ == "__main__":
        app = wx.App()
        TestFrame("")
        app.MainLoop()
    
f4lco
  • 3,728
  • 5
  • 28
  • 53
  • Thank you for this answer! If you have a look at my edit, I think your suggestion nr. 1 won't work for me. But I will try it with nr. 3 ;) – Munchkin Sep 25 '12 at 06:26