首页 > 解决方案 > 在 tkinter Text 小部件中获取位置

问题描述

我正在尝试找到一种可靠的方法来获取 tkinter 文本小部件中的当前光标位置。

到目前为止,我所拥有的是:

import tkinter as tk

def check_pos(event):
    print(t.index(tk.INSERT))

root = tk.Tk()

t = tk.Text(root)
t.pack()

t.bind("<Key>", check_pos)
t.bind("<Button-1>", check_pos)

root.mainloop()

但是,这会打印上一个光标位置而不是当前光标位置。有人知道发生了什么吗?

提前致谢。

标签: pythontkinter

解决方案


感谢 Bryan Oakley 通过他在评论中发布的链接为我指明了正确的方向。我选择了第三个选项,它引入了一个额外的绑定。工作代码如下。现在绑定发生在绑定类之后,以便函数可以看到 Text 小部件中的位置变化。

import tkinter as tk

def check_pos(event):
    print(t.index(tk.INSERT))

root = tk.Tk()

t = tk.Text(root)
t.pack()
t.bindtags(('Text','post-class-bindings', '.', 'all'))

t.bind_class("post-class-bindings", "<KeyPress>", check_pos)
t.bind_class("post-class-bindings", "<Button-1>", check_pos)


root.mainloop()

推荐阅读