在gtk.TextView中查找文本

时间:2010-03-02 14:58:16

标签: python gtk pygtk

我有gtk.Textview。我想以编程方式查找并选择此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 个答案:

答案 0 :(得分:4)

start_iter.forward_search会返回开始和结束匹配的元组,因此您的found变量中包含match_startmatch_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)