在gtk.TextView中查找文本
我有一个 gtk.Textview
,我想通过程序来查找并选中里面的一些文字。
我有一段代码,但它运行得不太对。
search_str = self.text_to_find.get_text()
start_iter = textbuffer.get_start_iter()
match_start = textbuffer.get_start_iter()
match_end = textbuffer.get_end_iter()
found = start_iter.forward_search(search_str,0, None)
if found:
textbuffer.select_range(match_start,match_end)
如果找到了文字,它就会选中 TextView
中的所有文字,但我只想选中找到的那部分文字。
1 个回答
6
start_iter.forward_search
会返回一个包含开始和结束匹配结果的元组,所以你的 found
变量里面同时有 match_start
和 match_end
。
这样应该就能正常工作了:
search_str = self.text_to_find.get_text()
start_iter = textbuffer.get_start_iter()
# don't need these lines anymore
#match_start = textbuffer.get_start_iter()
#match_end = textbuffer.get_end_iter()
found = start_iter.forward_search(search_str,0, None)
if found:
match_start,match_end = found #add this line to get match_start and match_end
textbuffer.select_range(match_start,match_end)