如何在tkinter中返回光标下的单词?

3
我希望制作一个具有自动完成功能的文本编辑器。我需要获取一些文本,以便与我想要提供自动完成的单词列表进行比较。这些文本可以是鼠标选择的文本(情况#1),也可以是光标下的单词(情况#2)。通过获取这些文本,我指的是将其作为字符串值返回。
使用tkinter能否实现这个功能?我不熟悉qt,但如果它可以实现这个功能,我会尝试使用它。
2个回答

5
要获取光标下字符的位置,您需要使用形式为"@x,y"的索引。您可以从事件或鼠标的当前位置获取x和y坐标。
特殊索引"sel.first""sel.last"(或Tkinter模块常量SEL_FIRSTSEL_LAST)给出当前选择中第一个和最后一个字符的索引。
以下是一个假想的示例。运行代码并移动鼠标以查看状态栏上打印了什么。
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 selected\n")
        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()

-2

您可以使用QTextEdit::cursorForPosition来获取鼠标位置的光标。之后,您可以调用QTextCursor::select并使用QTextCursor::WordUnderCursor来选择单词,再使用QTextCursor::selectedText来获取该单词。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接