2017-03-18 19 views
1

对Python完全陌生,所以我怀疑我犯了一个非常愚蠢的语法错误。没有通过部分传递的参数

from tkinter import * 
from functools import partial 

def get_search_results(keyword): 
    print("Searching for: ", keyword) 

def main(): 
    # ***** Toolbar ***** 
    toolbar = Frame(main_window) 
    toolbar.pack(fill=X) 

    toolbar_search_field = Entry(toolbar) 
    toolbar_search_field.grid(row=0, columnspan=4, column=0) 
    get_search_results_partial = partial(get_search_results, toolbar_search_field.get()) 
    toolbar_search_button = Button(toolbar, text="Search", command=get_search_results_partial) 
    toolbar_search_button.grid(row=0, column=5) 

main_window = Tk() 
main() 
main_window.mainloop() # continuously show the window 

基本上,这段代码创建一个带有搜索栏的窗口。我在搜索栏中输入了一些内容,当我按下按钮时,调用get_search_results方法。我在函数中传递关键字,使用部分。但是,该关键字未被打印到控制台。

+1

我怀疑你想要的东西更像是'拉姆达:get_search_results(toolbar_search_field.get())'。部分仍然在创建时获得价值。 – jonrsharpe

+0

可能重复[为什么Tkinter条目的get函数没有任何返回?](http://stackoverflow.com/questions/10727131/why-is-tkinter-entrys-get-function-returning-nothing) –

回答

2
get_search_results_partial = partial(get_search_results, toolbar_search_field.get()) 

这立即调用toolbar_search_field.get()(可能会得到一个空字符串),然后将其传递给部分。现在,get_search_results_partial是一个带有零参数的函数,它只是调用get_search_results('')。它没有连接到工具栏。

正如评论所说,只是这样做:

Button(toolbar, text="Search", command=lambda: get_search_results(toolbar_search_field.get())) 
+0

我没有完全了解拉姆达的工作方式,但这种方式很有效,所以谢谢! –