Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)?

like image 607
aless80 Avatar asked Jun 14 '26 21:06

aless80


2 Answers

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() 
like image 150
qfwfq Avatar answered Jun 17 '26 11:06

qfwfq


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)
like image 36
Dede95 Avatar answered Jun 17 '26 09:06

Dede95



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!