gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 22:51:18 24 4
gpt4 key购买 nike

我想制作一个具有自动完成功能的文本编辑器。我需要的是以某种方式获取由鼠标选择的文本(案例#1)或只是光标下的一个词(案例#2)以将其与我希望自动完成的单词列表进行比较。我所说的获取是指作为字符串值返回。

完全可以用 tkinter 完成吗?我对 qt 不熟悉,但如果可以实现该功能,我会尝试使用它。

最佳答案

要获取光标下的字符位置,您可以使用 "@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()

关于python - 如何在 tkinter 中返回光标下的单词?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21675320/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com