Reputation: 423
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
Reputation: 49318
You have a couple options.
self.on_ok
function, like '<Shift-Return>'
.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