简体   繁体   中英

How do I execute a callback when the Enter key is pressed after entering text into a Text widget?

I've really tried to find this out but have only discovered disconnected snippets such as tag_bind . I cannot work out how to use this (if indeed this is the right way forward).

I've got a Text widget into which the user can enter some text (such as a command or question) and I'd like to execute a function that reads that text then responds to it. Obviously I could provide a nearby Button widget which when clicked, reads the text in the Text widget. But I don't want people to have to move their hand from the keyboard to the mouse. I'd just like the callback to be triggered if they hit the Enter key. How do I do it please?

import Tkinter as tk

def on_enter(event):
    widget = event.widget
    print(widget.get())

root = tk.Tk()
entry = tk.Entry()
entry.pack(padx=5, pady=5)
entry.focus()
entry.bind('<Return>', on_enter)
root.mainloop()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM