如何从 Tkinter 文本框中获取索引 [英] How do I get the indices from the Tkinter textbox

查看:44
本文介绍了如何从 Tkinter 文本框中获取索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够从 Tkinter 文本框中突出显示的文本中获取索引(如 1.1 ...),有什么想法吗?

I'd like to be able to get the index (like 1.1...) out of a highlighted text in a Tkinter text box, any ideas?

推荐答案

所选文本带有标签sel".所选文本的开始和结束范围由sel.first"sel.last" 定义.如果您想获取文本,可以直接使用它们,如下所示:

The selected text has the tag "sel". The beginning and ending range of the selected text is defined by "sel.first" and "sel.last". You can use those directly if you want to get the text, like so:

chars = the_text_widget.get("sel.first", "sel.last")

如果您想要数字索引,则可以使用 index 方法将任何索引转换为其规范形式:

If, instead, you want the numerical index, you can use the index method which converts any index to its canonical form:

s0 = the_text_widget.index("sel.first")
s1 = the_text_widget.index("sel.last")

注意:tkinter 模块为这些定义了常量:SEL_FIRSTSEL_LAST 但我个人认为没有理由使用这些常量.使用它们的对应字符串同样简单,有助于强化选择只是另一个没有任何特殊属性的标签的概念.

Note: the tkinter module defines constants for these: SEL_FIRST and SEL_LAST but I personally see no reason to use these constants. Using their string counterparts is just as easy and helps reinforce the notion that the selection is just another tag without any special properties.

这篇关于如何从 Tkinter 文本框中获取索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆