1

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.

Human Cyborg Relations
  • 1,202
  • 5
  • 27
  • 52
  • 1
    I suspect what you want is more like `lambda: get_search_results(toolbar_search_field.get())`. The partial still gets the value at the point it's created. – jonrsharpe Mar 18 '17 at 23:46
  • Possible duplicate of [Why is Tkinter Entry's get function returning nothing?](http://stackoverflow.com/questions/10727131/why-is-tkinter-entrys-get-function-returning-nothing) – juanpa.arrivillaga Mar 18 '17 at 23:46

1 Answers1

2
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()))
Alex Hall
  • 34,833
  • 5
  • 57
  • 89