Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
174 views
in Technique[技术] by (71.8m points)

python - Is it possible to pass arguments into event bindings?

I haven't found an answer elsewhere and this doesn't appear to have been asked yet on SO.

When creating an event binding in wxPython, is it possible to pass additional arguments to the event? For example, this is the normal way:

b = wx.Button(self, 10, "Default Button", (20, 20))
        self.Bind(wx.EVT_BUTTON, self.OnClick, b)
def OnClick(self, event):
        self.log.write("Click! (%d)
" % event.GetId())

But is it possible to have another argument passed to the method? Such that the method can tell if more than one widget is calling it but still return the same value?

It would greatly reduce copy & pasting the same code but with different callers.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can always use a lambda or another function to wrap up your method and pass another argument, not WX specific.

b = wx.Button(self, 10, "Default Button", (20, 20))
        self.Bind(wx.EVT_BUTTON, lambda event: self.OnClick(event, 'somevalue'), b)
def OnClick(self, event, somearg):
        self.log.write("Click! (%d)
" % event.GetId())

If you're out to reduce the amount of code to type, you might also try a little automatism like:

class foo(whateverwxobject):
    def better_bind(self, type, instance, handler, *args, **kwargs):
        self.Bind(type, lambda event: handler(event, *args, **kwargs), instance)

    def __init__(self):
        self.better_bind(wx.EVT_BUTTON, b, self.OnClick, 'somevalue')

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...