问题描述
我有一个一般性的问题,我找不到真正的答案,因此希望你们能提供帮助.我有一个带有3个参数的函数,下面是我所拥有的示例.
I have a general question that I can't really find an answer to so hopefully you guys can help. I have a function that takes 3 parameters, below is an example of what I have.
def someFunction(self, event, string):
do stuff ..
self.canvas.bind("<Button-1>", self.someFunction("Hello"))
运行此命令时,我收到一条错误消息,说我传递了someFunction 2参数而不是3.我不确定为什么..
When I run this, I get an error saying that I passed someFunction 2 arguments instead of 3. I'm not sure why ..
推荐答案
在这里,您要绑定someFunction
的结果(或尝试这样做).之所以失败是因为,当python尝试获取someFunction
的结果时,当someFunction
确实需要2个显式参数时,它仅传递1个参数("Hello"
)进行调用.您可能想要类似的东西:
Here you're binding the result of someFunction
(or trying to anyway). This fails because when python tries to get the result of someFunction
, it calls it only passing 1 argument ("Hello"
) when someFunction
really expects 2 explicit arguments. You probably want something like:
self.canvas.bind('<Button-1>',lambda event: self.someFunction(event,"Hello"))
这将绑定一个新函数(由lambda
创建并环绕self.someFunction
),该函数将传递正确的参数.
This binds a new function (which is created by lambda
and wraps around self.someFunction
) which passes the correct arguments.
这篇关于Python Tkinter绑定具有多个参数的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!