问题
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 ;)
回答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()
来源:https://stackoverflow.com/questions/12570856/how-can-i-give-variables-to-the-event-handler