Event callback after a Tkinter Entry widget

ぃ、小莉子 提交于 2020-08-05 09:35:22

问题


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


回答1:


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



回答2:


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)


来源:https://stackoverflow.com/questions/39058817/event-callback-after-a-tkinter-entry-widget

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!