Get the word around the insertion point – Tkinter Text

Question:

So I want to get the word the user’s insertion point is "within". I’ve been trying multiple methods, such as my most recent being:

insert_idx = TEXT_EDITOR.index(INSERT)
word_start_index = TEXT_EDITOR.search(r"b", insert_idx, backwards=True, regexp=True)
    word_end_index = TEXT_EDITOR.search(r"b", insert_idx, regexp=True)

    word = ""
    print(word_start_index, word_end_index)
    if word_start_index and word_end_index:
        word = TEXT_EDITOR.get(f"{word_start_index}", f"{word_end_index}")

And many other methods before, too. They all either gave errors or just didn’t work.
I’m still learning Tkinter, so I don’t know if there’s a function that just does this, or if there’s some obvious method I’m overlooking.

Hello Stackover|flow

So basically in the image above, the insertion point is in the word "Stackoverflow". More specifically, in between the r and f. Now, what I’m trying to do is figure out how to set the variable "word" to "Stackoverflow".

Asked By: rezarg

||

Answers:

The text index allows for modifiers to an index. Two such modifiers are wordstart and wordend. So, to get the start and end of the word at the insertion point you can use "insert wordstart" and "insert wordend".

These modifiers are defined as follows:

?submodifier? wordstart – Adjust the index to refer to the first character of the word containing the current index. A word consists of any number of adjacent characters that are letters, digits, or underscores, or a single character that is not one of these. If the display submodifier is given, this only examines non-elided characters, otherwise all characters (elided or not) are examined.

?submodifier? wordend – Adjust the index to refer to the character just after the last one of the word containing the current index. If the current index refers to the last character of the text then it is not modified. If the display submodifier is given, this only examines non-elided characters, otherwise all characters (elided or not) are examined.

docs

Answered By: Bryan Oakley
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.