将参数传递给 Python 中的绑定函数 [英] Passing argument to bind function in Python

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

问题描述

#!/usr/bin/python3
from Tkinter import *

def keypress(key):
    print key, "pressed"

if __name__ == '__main__':
   root = Tk()
   root.bind('<Return>', keypress(key="enter"))
   root.bind('a', keypress(key="a"))
   root.mainloop()

我意识到程序一启动就会调用该函数,但我不知道如何将参数传递给 keypress 函数而不立即调用它.有人能解释一下如何解决吗?

I realize the function is being called as soon as the program starts but I don't know how to pass the arguments to the keypress function without invoking it immediately. Could someone explain how to fix it?

更新代码:

#!/usr/bin/python3
from Tkinter import *

def keypress(key):
    print key, "pressed"


root = Tk()
root.bind("<Return>", lambda event: keypress(key="enter"))
root.bind("a", lambda event: keypress(key="a"))
root.mainloop()

推荐答案

在你的 bind 函数调用中,你实际上是在调用函数,然后绑定函数的结果(也就是 ).您需要直接绑定函数.解决方案是 lambda .

In your bind function calls, you are actually calling the functions and then binding the result of the function (which is None) . You need to directly bind the functions. On solution is to lambda for that.

示例 -

root.bind('<Return>', lambda event: keypress(key="enter"))
root.bind('a', lambda event: keypress(key="a"))

如果您想将 event 参数传播到 keypress() 函数,您需要在函数中定义参数,然后传递它.示例 -

If you want to propagate the event parameter to the keypress() function, you would need to define the parameter in the function and then pass it. Example -

def keypress(event, key):
    print key, "pressed"
...
root.bind("<Return>", lambda event: keypress(event, key="enter"))
root.bind("a", lambda event: keypress(event, key="a"))

这篇关于将参数传递给 Python 中的绑定函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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