如何获取tkinter文本框中被搜索词的索引
我正在用tkinter制作一个用户界面。在这个界面里,有一个文本框,用户可以在里面写多行文字。我需要在这些文字中搜索特定的词,并把它们高亮显示。
目前,当我搜索一个词并尝试用tag_configure
和tag_add
来给它上色时,出现了一个错误,提示“坏索引”。
我在网上查了一些资料,了解到在tag_add
中使用的开始和结束索引是row.column
这种格式(如果我哪里错了,请纠正我)。
有没有人能帮我直接从tkinter的用户界面获取这种格式的索引,以便进行高亮显示?非常感谢!
1 个回答
8
这个数字必须是浮点数,比如文本中的第一个字符是 1.0
(而不是字符串 "1.0"
)
补充:我之前说错了。它可以是字符串,而且必须是字符串,因为 1.1
和 1.10
是相同的浮点数(正如 Bryan Oakley 所说的) - 不过我还是保留这个有效的例子。
from Tkinter import *
#------------------------------------
root = Tk()
#---
t = Text(root)
t.pack()
t.insert(0.0, 'Hello World of Tkinter. And World of Python.')
# create tag style
t.tag_config("red_tag", foreground="red", underline=1)
#---
word = 'World'
# word length use as offset to get end position for tag
offset = '+%dc' % len(word) # +5c (5 chars)
# search word from first char (1.0) to the end of text (END)
pos_start = t.search(word, '1.0', END)
# check if found the word
while pos_start:
# create end position by adding (as string "+5c") number of chars in searched word
pos_end = pos_start + offset
print pos_start, pos_end # 1.6 1.6+5c :for first `World`
# add tag
t.tag_add('red_tag', pos_start, pos_end)
# search again from pos_end to the end of text (END)
pos_start = t.search(word, pos_end, END)
#---
root.mainloop()
#------------------------------------