python - 在循环中使用 lambda 自动绑定(bind)

标签 python tkinter

<分区>

我目前正在尝试创建一个循环,将事件 Action 对绑定(bind)到字典中。 回调函数只是调用 Action 函数并打印参数。

for binding, action in self.keyMap.revMap.items() :
        print binding, action
        self.top.bind(binding,
                      lambda event : self.callback(event, self.actionRep.__class__.__dict__[action]))

    print self.top.bind()

在绑定(bind)时,我得到这些日志:

<Escape> toggleMenu -------------generated by the line "print binding, action"
<Return> toggleChat -------------generated by the line "print binding, action"
('<Key-Return>', '<Key-Escape>', '<Key>') ---generated by the line "print self.top.bind()"

事件- Action 对是正确的。 但是,当事件发生时,我有这个:

<Tkinter.Event instance at 0x0000000002BB3988> <function toggleChat at 0x0000000002B60AC8>
<Tkinter.Event instance at 0x0000000002BB3948> <function toggleChat at 0x0000000002B60AC8>

也就是说,escape 和 return 事件似乎都绑定(bind)到 toggleChat...

我对 lambda 表达式没有什么经验,但我希望为每个循环创建一个新的无名函数。我错了吗?如果不是,问题出在哪里?

提前感谢您的见解。

最佳答案

为 lambda 创建闭包的习惯用法是通过默认参数传递您希望绑定(bind)的对象

self.top.bind(binding, lambda event, action=action: self.callback(event, self.actionRep.__class__.__dict__[action]))

关于python - 在循环中使用 lambda 自动绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16653538/

相关文章:

python - 在 Tkinter 中动态改变 Canvas 的滚动区域

python - 在 wxpython 应用程序中导入 tkinter 小部件作为面板

python - 在 matplotlib 注释中格式化数学文本

python - Postgres psycopg2 创建用户

python - 用 Python 3 中的列表或字典中的内容替换字符串的内容

python-3.x - tkinter 用户输入小部件到 xlsx

python - 按钮释放 Tkinter

python - OptionMenu 命令函数需要参数

python - 如何将 python 代码转换为解析树并返回原始代码?

python - 将数据从 Django View 传递到 D3