How do I return word under cursor in tkinter?

Question:

I want to make a text editor with autocompletion feature. What I need is somehow get the text which is selected by mouse (case #1) or just a word under cursor(case #2) to compare it against a list of word I want to be proposed for autocompletion. By get I mean return as a a string value.

How can I do this with TKinter?

Asked By: user3292534

||

Answers:

You can use QTextEdit::cursorForPosition to get a cursor for mouse position. After that you can call QTextCursor::select with QTextCursor::WordUnderCursor to select the word and QTextCursor::selectedText to get the word.

Answered By: Pavel Strakhov

To get the character position under the cursor, you use an index of the form "@x,y". You would get the x and y coordinates from an event, or from the current position of the mouse.

The special index "sel.first" and "sel.last" (or the Tkinter module constants SEL_FIRST, SEL_LAST) give you the index of the first and last characters in the current selection.

Here’s a contrived example. Run the code, and move your mouse around to see what is printed on the status bar.

import Tkinter as tk

class Example(tk.Frame):
    def __init__(self, parent):
        tk.Frame.__init__(self, parent)

        self.status = tk.Label(anchor="w", text="woot")
        self.text = tk.Text(wrap="word", width=60, height=10)
        self.status.pack(side="bottom", fill="x")
        self.text.pack(side="top", fill="both", expand=True)

        self.text.insert("1.0", "Move your cursor around to see what " +
                         "index is under the cursor, and what " +
                         "text is selectedn")
        self.text.tag_add("sel", "1.10", "1.16")

        # when the cursor moves, show the index of the character
        # under the cursor
        self.text.bind("<Any-Motion>", self.on_mouse_move)

    def on_mouse_move(self, event):
        index = self.text.index("@%s,%s" % (event.x, event.y))
        ch = self.text.get(index)
        pos = "%s/%s %s '%s'" % (event.x, event.y, index, ch)
        try:
            sel = "%s-%s" % (self.text.index("sel.first"), self.text.index("sel.last"))
        except Exception, e:
            sel = "<none>"
        self.status.configure(text="cursor: %s selection: %s" % (pos, sel))


if __name__ == "__main__":
    root = tk.Tk()
    Example(root).pack(fill="both", expand=True)
    root.mainloop()
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.