简体   繁体   English

如何将字符偏移量转换为“文本”小部件的列行号位置?

[英]How to convert character offset to Text widget's column line number position?

I have a text widget with some text. 我有一个带有一些文本的文本小部件。 Within the text from characters 424 to 478 I would like to change its color using tag_add(). 在从字符424到478的文本中,我想使用tag_add()更改其颜色。

The problem is that tag_add() requires positioning in "6.15" format, meaning sixth line fifteenth character. 问题在于tag_add()需要以“ 6.15”格式定位,这意味着第六行第十五个字符。 However I don't know how many new lines precede the 424th character nor what is the remainder to calculate the exact column. 但是我不知道在第424个字符前有多少行,也没有多少可以计算出确切的列。 Is there a method to convert from an absolute byte offset to line/column index? 有没有一种方法可以将绝对字节偏移量转换为行/列索引?

The text widget supports a limited expression syntax with indexes. 文本小部件支持带索引的有限表达语法。 Among other things you can add and subtract characters from an index. 除其他功能外,您还可以在索引中添加和减去字符。 For example, you can use "1.0 + 100 chars" (or "1.0+100c" ) to mean "line one, character zero, plus 100 characters". 例如,您可以使用"1.0 + 100 chars" (或"1.0+100c" )来表示“第一行,零字符,再加上100个字符”。

The official python documentation punts on documenting this, choosing to refer you to the offical tcl/tk documentation here: http://tcl.tk/man/tcl8.5/TkCmd/text.htm#M16 官方python文档对此文档进行了修饰,请选择此处以参考正式的tcl / tk文档: http : //tcl.tk/man/tcl8.5/TkCmd/text.htm#M16

This is also documented on the effbot site here: http://effbot.org/tkinterbook/text.htm (see the section "Expressions") 这也记录在effbot网站上: http ://effbot.org/tkinterbook/text.htm(请参见“表达式”部分)

If you are using insert() to add the text, you can specify the tag to use during the insert: 如果使用insert()添加文本,则可以指定要在插入过程中使用的标签:

textw.tag_configure('red', background='red')

textw.insert(END, 'Some sample text ', (), 'with a bit of red', 'red', ' in the middle.')

Results in: 结果是:

在此处输入图片说明

Also, depending on how your text is configured you can use: 另外,根据文本的配置方式,您可以使用:

textw.tag_add('red', 1.424, 1.478)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM