Jython Swing:在按下按钮时传递的不仅仅是自我和事件 [英] Jython Swing: Passing more than self and event on a button press

查看:72
本文介绍了Jython Swing:在按下按钮时传递的不仅仅是自我和事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在Jython的循环中创建几个摆动的JButtons按钮.按下时,每个按钮应调用相同的功能,但具有一个不同的参数.我无法在self和event之外传递任何参数.

I'm creating a couple of swing JButtons buttons in a loop in Jython. On press, each button should call the same function, but with one different parameter. I'm having trouble passing any parameters outside of self, and event.

这有效:

for x in range(0,3):
    name = JButton(str(x))
    name.actionPerformed = self.foo

def foo(self, event):
    print "I work."

神奇地将事件传递给方法.

Somehow event magically is passed to the method.

这不是:

for x in range(0,3):
    name = JButton(str(x))
    name.actionPerformed = self.foo(x)

def foo(self, event, number):
    print "I don't work."
    print str(number)

我所看到的问题是,当我添加任何参数时我不在,我不再传递事件,并且最终出现一个错误,告诉我"foo()恰好接受了3个参数(给定2个)" .我知道了,但是如何从按钮中提取事件?

The issue as I see it, it that I'm not when I add any argument, I no longer pass an event and I end up with an error telling me "foo() takes exactly 3 arguments (2 given)". I get that, but how can I extract the event from the button?

推荐答案

回调仅接受调用它的代码(GUI工具包)传递的内容.如果您要传递更多信息,并且您无法说服调用者执行以下操作:传递一些额外的东西,你就不走运了.

A callback only takes what the code calling it (the GUI toolkit) passes in. If you want to pass in more and you can't convince said caller to pass on something extra, you're out of luck.

但是幸运的是,存在一个漏洞:您可以传递任意可调用对象,并且可以构造部分函数,​​这些函数包装了另一个函数,记住了每次调用时都要传递的其他参数.

But luckily, there's a loophole: You can pass arbitrary callables, and you can construct partial functions, which are functions wrapping another function, remembering additional arguments to pass along whenever they are called.

import functools

def callback(x, y):
    return x + y

g = functools.partial(callback, y=3)
g(2) #=> 5

存在一些奇怪的参数顺序问题(例如,如果第一个参数是通过关键字参数提供的,则无法轻松地调用带有位置参数的局部变量),但是您的用例(将参数添加到参数列表的末尾)应该工作得很好.您只需要使用关键字参数即可.

There are a few issues with strange argument orders (e.g. you can't easily call partial with positional arguments if the first argument was supplied via keyword argument), but your use case (add arguments to the end of the argument list) should work just fine. You just need to use keyword arguments.

这篇关于Jython Swing:在按下按钮时传递的不仅仅是自我和事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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