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

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

问题描述

我在其他地方没有找到答案,SO 上似乎也没有人问过这个问题.

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)
" % 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)
" % 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天全站免登陆