0

I followed an already answered question here but not able to get it work for some reasons. Sample code is below which I tried and where I am facing problem.

from Tkinter import * 
import Tkinter as tk

root = Tk()

textbox = Text(root)
textbox.insert(INSERT, "Hello, world!\n")
textbox.insert(END, "i highlight you, you hightlight him, he highlights me...loop it")
textbox.pack(expand=1, fill=BOTH)

class CustomText(tk.Text):

    def __init__(self, *args, **kwargs):
        tk.Text.__init__(self, *args, **kwargs)

    def highlight_pattern(self, pattern, tag, start="1.0", end="end",
                          regexp=False):
        '''Apply the given tag to all text that matches the given pattern

        If 'regexp' is set to True, pattern will be treated as a regular
        expression.
        '''

        start = self.index(start)
        end = self.index(end)
        self.mark_set("matchStart", start)
        self.mark_set("matchEnd", start)
        self.mark_set("searchLimit", end)

        count = tk.IntVar()
        while True:
            index = self.search(pattern, "matchEnd","searchLimit",
                                count=count, regexp=regexp)
            if index == "": break
            self.mark_set("matchStart", index)
            self.mark_set("matchEnd", "%s+%sc" % (index, count.get()))
            self.tag_add(tag, "matchStart", "matchEnd")

CustomText()

textbox.tag_configure("red", foreground="red")
textbox.highlight_pattern("loop it", "red")    

root.mainloop()

I get a following error:

textbox.highlight_pattern("loop it", "red")    
AttributeError: Text instance has no attribute 'highlight_pattern'

What I want:

I understood the error, but I don't get how should I highlight loop it or any text that is there in my textbox using the class mentioned in that link. This sounds really simple, but I am still not able to figure out how I should use this class.

Community
  • 1
  • 1
Radheya
  • 779
  • 1
  • 11
  • 41

1 Answers1

1

Change this:

textbox = Text(root)

To this:

textbox = CustomText(root)

And, of course, you'll have to rearrange your code so that the class is defined before you use it.

Bryan Oakley
  • 370,779
  • 53
  • 539
  • 685