Mike - SMT
Mike - SMT

Reputation: 15226

How do I .bind Enterkey <Return> to a button only if inside textbox?

I have A Note Taking Program and currently I can type in a Keyword in TextBox-1 and hit Enter to get my notes displayed in a TextBox-2.

The only way I can find how to bind Enter to a button is for it to always be bound to that button. Or I can bind Enter to a function. I would rather have it bound to the button/function only if I am currently inside textBox-1.

I don't even know if it is possible because I can not find any references to something similar to my needs.

Currently I have my Enter key bound like this:

root.bind('<Return>', kw_entry)

This calls the function kw_entry when I hit Enter.

def kw_entry(event=None):
    e1Current = keywordEntry.get().lower()
    if e1Current in notes:  # e1Corrent is just the current text in TextBox-1
        root.text.delete(1.0, END)
        root.text.insert(tkinter.END, notes[e1Current])
        root.text.see(tkinter.END)
    else:
        root.text.delete(1.0, END)
        root.text.insert(tkinter.END, "Not a Keyword")
        root.text.see(tkinter.END)

For the most part this works fine however I also want to edit the notes being displayed and the problem is I can not hit Enter while in TextBox-2 because Enter is bound to call the function kw_entry. This is a problem because it resets everything in TextBox-2.

Can anyone point me in the right direction?

Upvotes: 1

Views: 60

Answers (1)

Bryan Oakley
Bryan Oakley

Reputation: 385910

If you only want the binding to apply when focus is on a specific widget, put the binding on that widget.

In the following example, if you press return while in the text widget then a message will be printed on the console. If you are in the entry widget, that won't happen.

import tkinter as tk

def foo(event):
    print("you pressed return")
    # the following prevents the enter key from inserting
    # a newline. If you remove the line, the newline will
    # be entered after this function runs
    return "break"

root = tk.Tk()

entry = tk.Entry(root)
text = tk.Text(root)

entry.pack(side="top", fill="x")
text.pack(side="bottom", fill="both", expand=True)

text.bind("<Return>", foo)

root.mainloop()

Upvotes: 1

Related Questions