根据列表中的位置更改 Tkinter 文本小部件中某些单词的颜色
Change color of certain words in Tkinter Text widget based on position in list
我有一个 tkinter 文本框,我想根据特定单词在列表中的位置更改它们的颜色。基本上我有列表 foo = [1,4,5,8,9]
,我想更改与列表中的数字对应的单词的颜色。因此,位置 1、4、5、8 和 9 中的单词应该更改颜色。我看过不同的答案,但它们是根据关键字而不是给定单词的位置来操作的。
突出显示文本的方法是创建一个标签,使用您想要的任何属性(前景、背景、字体等)配置标签,然后将该标签应用于文本区域。剩下的只是计算要突出显示的字符范围的简单数学。
text = tk.Text(...)
text.tag_configure("highlight", background="yellow")
...
# add the tag "highlight" to the characters between index 3.0 and 4.0
text.tag_add("highlight", "3.0", "4.0")
为了帮助突出显示单词,您可以使用带有索引的修饰符 "wordstart"
and/or "wordend"
来获取 tcl 认为完整单词的开头和结尾。
# add the tag "highlight" to the word at position 4.5
text.tag_add("highlight", "4.5 wordstart", "4.5 wordend")
我有一个 tkinter 文本框,我想根据特定单词在列表中的位置更改它们的颜色。基本上我有列表 foo = [1,4,5,8,9]
,我想更改与列表中的数字对应的单词的颜色。因此,位置 1、4、5、8 和 9 中的单词应该更改颜色。我看过不同的答案,但它们是根据关键字而不是给定单词的位置来操作的。
突出显示文本的方法是创建一个标签,使用您想要的任何属性(前景、背景、字体等)配置标签,然后将该标签应用于文本区域。剩下的只是计算要突出显示的字符范围的简单数学。
text = tk.Text(...)
text.tag_configure("highlight", background="yellow")
...
# add the tag "highlight" to the characters between index 3.0 and 4.0
text.tag_add("highlight", "3.0", "4.0")
为了帮助突出显示单词,您可以使用带有索引的修饰符 "wordstart"
and/or "wordend"
来获取 tcl 认为完整单词的开头和结尾。
# add the tag "highlight" to the word at position 4.5
text.tag_add("highlight", "4.5 wordstart", "4.5 wordend")