0

I got the pattern highlighting from: How to highlight text in a tkinter Text widget

But I have been trying to improve it, though i failed. The problem is that if the pattern is "read", it will still highlight "read" from "readily" or something else with "read" on it. here's the sample code:

from tkinter import *

class Ctxt(Text): # Custom Text Widget with Highlight Pattern   - - - - -
    # Credits to the owner of this custom class - - - - - - - - - - - - -
    def __init__(self, *args, **kwargs):
        Text.__init__(self, *args, **kwargs)

    def highlight_pattern(self, pattern, tag, start="1.0", end="end",
                          regexp=False):
        start = self.index(start)
        end = self.index(end)
        self.mark_set("matchStart", start)
        self.mark_set("matchEnd", start)
        self.mark_set("searchLimit", end)
        count = 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")
    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -


# Root Window Creation  - - - -
root = Tk()
root.geometry("320x240")
root.title("Sample GUI")
# - - - - - - - - - - - - - - -


# Text Widget - - - - - - - - - - - - - - -
Wtxt = Ctxt(root)
Wtxt.pack(expand = True, fill= BOTH)
Wtxt.insert("1.0","red read rid ready readily")
# - - - - - - - - - - - - - - - - - - - - -

# Highlight pattern - - - - - - - - -
Wtxt.tag_config('green', foreground="green")
Wtxt.highlight_pattern('read','green')



# Mainloop  -
mainloop()
# - - - - - -

I would like to have some help to make it color only when the word is "read" and nothing around it.

Community
  • 1
  • 1
Ako Cruz
  • 343
  • 1
  • 2
  • 12

1 Answers1

1

You need to set the regexp flag to True, then use an appropriate regular expression. Note that the regex must follow the rules of Tcl regular expressions.

For your case you want to only match the pattern as a whole word, so you can use \m to match the beginning of a word and \M to match the end of a word:

Wtxt.highlight_pattern('\mread\M','green', regexp=True)
Bryan Oakley
  • 370,779
  • 53
  • 539
  • 685