Ecko
Ecko

Reputation: 1080

Detect whether or not cursor is in Text widget

I am writing a text editor in Python 3 with tkinter, and I'm trying to add an undo function, but in order to log the user's edits I need to log the edit when they type a letter. However, I don't want to log the typed letter if they have clicked out of the text widget. My question is this:

Can I detect whether or not the Text widget's cursor is in the widget? Is there an attribute on the text widget, or a bind I can put on the master window to detect if the cursor is in the text widget?

Upvotes: 0

Views: 1730

Answers (1)

Bryan Oakley
Bryan Oakley

Reputation: 385900

If your bindings are on the text widget, and if the focus is not on the text widget, your text widget will never see the keypress. Focus management is built in to Tkinter, so you shouldn't have to do anything.

To answer your specific question, you can use the method focus_get to retrieve the widget that currently has keyboard focus. You can also bind to <FocusIn> and <FocusOut> to be notified when the widget gains or loses focus.

Also, are you aware that the text widget has a built-in undo facility? The New Mexico Tech website has a nice brief overview: http://infohost.nmt.edu/tcc/help/pubs/tkinter/web/text-undo-stack.html

Upvotes: 4

Related Questions