[英]Function called by the control flow, not by tkinter bind
我有以下功能
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
觸發事件時將調用回調函數。
就像@ddelemeny所說的那樣,該函數將在編寫時被調用。 如果將程序構造為類,則通常不需要傳遞參數,因為您可以直接從函數中與變量進行交互。 但是,針對您的情況的簡單解決方案是使用lambda
表達式,因此Python在控制流到達時不會調用回調函數。
listbox.bind("<Return>", lambda e: insert_word(t_start,listbox.get(ACTIVE)))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.