我希望制作一个具有自动完成功能的文本编辑器。我需要获取一些文本,以便与我想要提供自动完成的单词列表进行比较。这些文本可以是鼠标选择的文本(情况#1),也可以是光标下的单词(情况#2)。通过获取这些文本,我指的是将其作为字符串值返回。
使用tkinter能否实现这个功能?我不熟悉qt,但如果它可以实现这个功能,我会尝试使用它。
使用tkinter能否实现这个功能?我不熟悉qt,但如果它可以实现这个功能,我会尝试使用它。
"@x,y"
的索引。您可以从事件或鼠标的当前位置获取x和y坐标。"sel.first"
和"sel.last"
(或Tkinter模块常量SEL_FIRST
,SEL_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()
您可以使用QTextEdit::cursorForPosition
来获取鼠标位置的光标。之后,您可以调用QTextCursor::select
并使用QTextCursor::WordUnderCursor
来选择单词,再使用QTextCursor::selectedText
来获取该单词。