python - 在 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()
但是,这会打印上一个光标位置而不是当前光标位置。有人知道发生了什么吗?
提前致谢。
解决方案
感谢 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()
推荐阅读
- c++ - 如何为std函数分配空间并做memcpy?
- c# - 与 Promise.all 等效的 C# 是什么?
- bash - Mutt bash脚本可以从命令行发送电子邮件,但不能从motioneye通知钩子发送电子邮件
- javascript - 如何将对象数组转换为逗号分隔的字符串?
- google-apps-script - 关于单元格选择
- c++ - 如何使用终端命令从 C++ 程序中打开多个图像?
- javascript - 将范围滑块绑定到图像序列
- angular - 在反应式表单模块的 auditTime 方法的订阅块中测试值
- php - 连接两个 MySQL 表并在表中显示结果
- spring-boot - 自定义 AOP Spring Boot 注解