Jython Swing:按下按钮时传递的不仅仅是自身和事件
我正在 Jython 中循环创建几个 Swing JButtons 按钮。按下时,每个按钮都应调用相同的函数,但具有一个不同的参数。我在传递 self 和 event 之外的任何参数时遇到问题。
这是有效的:
for x in range(0,3):
name = JButton(str(x))
name.actionPerformed = self.foo
def foo(self, event):
print "I work."
事件以某种方式神奇地传递给该方法。
这不是:
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 个参数) )”。我明白了,但是如何从按钮中提取事件呢?
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.
This works:
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.
This doesn't:
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)
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
回调仅接受调用它的代码(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.
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.
我同意德尔南的答案,但我确实找到了另一个更具体的解决方案,我将在这种情况下使用它,并认为值得传递。
无需向函数调用添加附加信息,而是使用传递的事件来获取有关调用者的信息相当容易。
IE
I'm going with delnan's answer, but I did find another more problem specific solution that I'm going to use in this case and thought it would be worth passing along.
Instead of adding additional information to the function call, it's rather easy to use the event passed to get information on the caller.
I.E.