Robert Błaszczyk
Robert Błaszczyk

Reputation: 1

input entry text with bind in tKinter (Python)

I created an entry widget inside a function.

search_1=Entry(okno, width=45)
search_1.grid( row=3, column=1)
#okno is main window of tK

Then I tried to get variable from it with

search_1.bind("<Return>", lambda event, a=search_1.get(), b="AUTOR": activate(a, b)) 

However function activate receives only b variable, which is a defined string. "a" variable which is supposed to be text from search_1 entry is not passed. any idea why?

I tried to read that value (search_1.get()) in a activate function, but an entry widget is not global. I would prefer to use bind/lambda though.

Upvotes: 0

Views: 3730

Answers (1)

Bryan Oakley
Bryan Oakley

Reputation: 386220

The problem is that you're calling search_1.get() at the time the binding is created, not at the time that the user presses the return key.

You should stop using a lambda in this case and use a proper function. They are much easier to write, read, and debug. You can also leverage the fact that bound functions will passed an object that contains a reference to the widget that received the event. This makes the code less reliant on global variables, which is almost always a good thing.

def do_search(event):
    a=event.widget.get()
    b="AUTOR"
    activate(a, b)
...
search_1.bind("<Return>", do_search)

With that, you can much more easily debug issues.

Upvotes: 2

Related Questions