参数未通过部分
Argument not being passed through partial
对 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
基本上,这段代码创建了一个带有搜索栏的 window。我在搜索栏中输入了一些内容,当我按下按钮时,调用了 get_search_results 方法。我在函数中传递关键字,使用部分。但是,关键字没有打印到控制台。
get_search_results_partial = partial(get_search_results, toolbar_search_field.get())
这会立即调用 toolbar_search_field.get()
(可能得到一个空字符串),然后将其传递给 partial。现在 get_search_results_partial
是一个零参数的函数,它只调用 get_search_results('')
。它与工具栏没有关联。
按照评论中的建议,只需这样做:
Button(toolbar, text="Search", command=lambda: get_search_results(toolbar_search_field.get()))
对 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
基本上,这段代码创建了一个带有搜索栏的 window。我在搜索栏中输入了一些内容,当我按下按钮时,调用了 get_search_results 方法。我在函数中传递关键字,使用部分。但是,关键字没有打印到控制台。
get_search_results_partial = partial(get_search_results, toolbar_search_field.get())
这会立即调用 toolbar_search_field.get()
(可能得到一个空字符串),然后将其传递给 partial。现在 get_search_results_partial
是一个零参数的函数,它只调用 get_search_results('')
。它与工具栏没有关联。
按照评论中的建议,只需这样做:
Button(toolbar, text="Search", command=lambda: get_search_results(toolbar_search_field.get()))