Python tkinter 绑定具有多个参数的函数 [英] Python tkinter binding a function with multiple parameters

查看:30
本文介绍了Python tkinter 绑定具有多个参数的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个普遍的问题,我真的找不到答案,所以希望你们能提供帮助.我有一个接受 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 ..

推荐答案

在这里,您要绑定 someFunctionresult(或尝试绑定).这失败了,因为当 python 尝试获取 someFunction 的结果时,它只在 someFunction 真正期望时调用它传递 1 个参数 ("Hello")2 显式参数.你可能想要这样的东西:

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 绑定具有多个参数的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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