Karpov
Karpov

Reputation: 423

tkinter: bind Return key to the OK button -- but not to the Text widget

With tkinter/ttk (8.5+), in a custom dialog, I want to bind the Return key to the OK button. So I use the standard instruction:

self.window.bind("<Return>", self.on_ok)

The problem is, in this custom dialog there is also a (multiline) Text widget. And once the Return key is bound to the OK button, it's no longer possible to type Enter in the Text widget without terminating the dialog! Typing Return is now equivalent to pressing OK.

I checked in Firefox and, when a Text control has the focus, pressing Return doesn't fire the OK button. It justs enters a newline character. If the OK button has the focus, then pressing Return activates the button.

Is there a way of reproducing this behavior in tkinter? Meaning, a binding that fires the OK button only if the Text widget is not selected?

Upvotes: 0

Views: 1551

Answers (1)

TigerhawkT3
TigerhawkT3

Reputation: 49318

You have a couple options.

  1. Choose a different binding for the self.on_ok function, like '<Shift-Return>'.
  2. Have the function check for which widget has focus. If self.window is your root tkinter object:

 

def on_ok(event):
    if self.window.focus_get() == text:
        print('the text widget has focus')
    else:
        print('some other widget has focus')

Upvotes: 2

Related Questions