aless80
aless80

Reputation: 3342

Event callback after a Tkinter Entry widget

From the first answer here: StackOverflow #6548837 I can call callback when the user is typing:

from Tkinter import *

def callback(sv):
    print sv.get()

root = Tk()
sv = StringVar()
sv.trace("w", lambda name, index, mode, sv=sv: callback(sv))
e = Entry(root, textvariable=sv)
e.pack()
root.mainloop() 

However, the event occurs on every typed character. How to call the event when the user is done with typing and presses enter, or the Entry widget loses focus (i.e. the user clicks somewhere else)?

Upvotes: 2

Views: 10241

Answers (2)

Dede95
Dede95

Reputation: 41

To catch Return key press event, the standard Tkinter functionnality does it. There is no need to use a StringVar.

def callback(event):
  pass #do the work

e = Entry(root)
e.bind ("<Return">,callback)

Upvotes: 3

qfwfq
qfwfq

Reputation: 2526

I think this does what you're looking for. I found relevant information here. The bind method is the key.

from Tkinter import *

def callback(sv):
    print sv.get()

root = Tk()

sv = StringVar()
e = Entry(root, textvariable=sv)
e.bind('<Return>', (lambda _: callback(e)))

e.pack()
root.mainloop() 

Upvotes: 9

Related Questions