问题描述
限时送ChatGPT账号..我正在尝试找到一种可靠的方法来获取 tkinter 文本小部件中的当前光标位置.
I'm trying to find a reliable way of getting the current cursor position in a tkinter text widget.
到目前为止我所拥有的是:
What I have so far is:
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()
然而,这会打印前一个光标位置而不是当前位置.任何人都知道发生了什么?
However, this prints the previous cursor position and not the current one. Anyone have any ideas what is going on?
提前致谢.
推荐答案
感谢 Bryan Oakley 通过他在评论中发布的链接为我指明了正确的方向.我选择了第三个选项,它引入了额外的绑定.工作代码如下.现在绑定发生在类绑定之后,以便函数可以看到 Text 小部件中位置的变化.
Thanks to Bryan Oakley for pointing me in the right direction with the links he posted in the comments. I chose the third choice which introduces an additional binding. The working code is below. Now the binding happens after the class is bound so that the change of position in the Text widget is visible to the function.
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()
这篇关于在 tkinter Text 小部件中获取位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
更多推荐
[db:关键词]
发布评论