在 tkinter Text 小部件中获取位置

编程入门 行业动态 更新时间:2024-10-23 18:26:16
本文介绍了在 tkinter Text 小部件中获取位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送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:关键词]

本文发布于:2023-04-30 06:32:41,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1390742.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:部件   位置   tkinter   Text

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!