Regex and Tkinter

Martin Franklin martin.franklin at westgeo.com
Mon Nov 19 10:16:03 CET 2001


Jeffrey Dunnett wrote:

> What I am trying to do is implement a find, find next option on a
> Tkinter\Python program usings reg. expressions what I am not sure about
> how to do is how to A) Get the information location in the string where
> the regex was found B) Hightlight the text in the text box on scree.
> 
> So far I have a created text box with some text in it and am doing this
> 
> def findregegx(self):
> 
>     #Gets the regex from a entry widget created earlier in the class
>     self.expression = self.regexp_entry.get()
> 
>     #Gets the text from the text field created earlier, self. index = 1.0
>     self.search_text = self.display.articleArea.listbox.get(self.index,
>     END)
> 
>     #Searching for the regex
>     found = re.search(self.expression, self.search_text)
> 
>     print found.group()
> 
> 
> I figure that I can hightlight the text by using tags in some way but I
> am not quite certain how to go about finding where the regext is in the
> text field.  Any help would be appreciated.
> 
> Jeff Dunnett
> 
> 

Jeff,

The Tkinter Text widget has a search method.....  i'm just not sure if it 
will take a re as it's argument, however this is the simplest way of 
'finding' some text inside the text widget as it returns the position  of 
the 'found' text so you can set the selection tag.....


here is a quick example but you should also consider looking at the IDLE 
source code for a different aproach - in fact (i've just taken another 
look) and they don't use the Text widget search method so you should really 
take a look....

# textarea is a Pmw.ScrolledTextBox
# pattern is an Entry box

    def find_text(self):
        self.parent.textarea.tag_delete("found")
        pat=self.pattern.get()
        if not pat:
            return
        self.found=self.parent.textarea.search(pat, "insert")
        if self.found:
            self.show()
            
            
    def show(self):
        line, start = map(int, self.found.split('.'))
        end=start+len(self.pattern.get())
        self.parent.textarea.tag_add("found", "%d.%d" %(line, start
            "%d.%d" %(line, end))
        self.parent.textarea.tag_config("found", background='navy',       
            foreground='white')
        self.parent.textarea.mark_set("insert", "%d.%d" %(line, end+1))
        self.parent.textarea.see("%d.%d" %(line, start))
        self.parent.textarea.update()
        

HTH
Martin





More information about the Python-list mailing list