可以将参数传递到事件绑定中吗? [英] Is it possible to pass arguments into event bindings?

查看:114
本文介绍了可以将参数传递到事件绑定中吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我没有在其他地方找到答案,这似乎并没有被问到。

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

在wxPython中创建事件绑定时,是否可能传递额外的参数到事件?例如,这是正常的方式:

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)\n" % 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.

推荐答案

您可以随时使用lambda或其他函数来包装方法并传递另一个参数,不是WX具体的。

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)\n" % 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')

这篇关于可以将参数传递到事件绑定中吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆