我有以下功能
def insert_word(listbox,text):
t_start.insert(INSERT, text)
print "worked"
通过以下方式绑定到“ <Return>”键
listbox.bind("<Return>", insert_word(t_start,listbox.get(ACTIVE)))
为什么在控制流到来时而不是在按Return键时调用该函数?如果可以以其他方式触发绑定功能,那么绑定功能背后的整个思想是什么?
我需要一个带有__init__
和__call__
方法的类来解决此问题吗?
之所以调用该函数,是因为您实际上正在调用它。
listbox.bind("<Return>", insert_word(t_start,listbox.get(ACTIVE)))
# ^----this function call is evaluated---^
您要做的是为绑定提供一个回调,即一个函数对象。您可以使用闭包来做到这一点。
def callback(t_start, text):
def inner():
t_start.insert(INSERT, text)
return inner # Return the function
listbox.bind("<Return>", callback(t_start, listbox.get(ACTIVE)) )
# ^----this call returns a function----^
# Be aware that ^--this parameter-^ is
# still evaluated when the interpreter
# evaluates the statement
触发事件时将调用回调函数。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句