Human Cyborg Relations
Human Cyborg Relations

Reputation: 1244

Argument not being passed through partial

Completely new to Python, so I suspect I'm making a very stupid syntax mistake.

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

Basically, this code creates a window with a search bar. I input something in the search bar, and when I press the button, the get_search_results method is called. I'm passing the keyword in the function, using a partial. However, the keyword is not being printed to the console.

Upvotes: 1

Views: 57

Answers (1)

Alex Hall
Alex Hall

Reputation: 36043

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

This calls toolbar_search_field.get() immediately (presumably getting an empty string) and then passes it to partial. Now get_search_results_partial is a function with zero arguments that just calls get_search_results(''). It has no connection to the toolbar.

As suggested in the comments, just do this:

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

Upvotes: 2

Related Questions