How to search for whole words in a text widget?

75 Views Asked by At

I am Working on a Python Text Editor With Python and tkinter. But I Have Some Problems with changing font color of the text widget.
I have just started writing.
Its been just 5 mins till then.

Here is editor.py

##imports
from tkinter import Tk,Text,BOTH,font
from font import fontify

##When the text gets edited
def Keyboardpress(key):
    editarea_text = editArea.get("1.0","end")
    ##Calling the fontify function for doing some chill!
    fontify(editArea,editarea_text)

##Creating Window
editor = Tk()

##resizing editor
editor.geometry("400x400")

##creating a font
myFont = font.Font(family='Courier',size = 24,weight = "normal")

##Here goes the ui
editArea = Text(editor,bg="#333",fg="#eee",height = 400,width = 400,font = myFont)
editArea.bind('<key>',print())
editArea.pack(fill = BOTH)

##binding Button press with editor
editor.bind( '<Key>', lambda i : Keyboardpress(i))

##Excecuting Window
editor.mainloop()

**And This is font.py**
keywords = ["False","await","else","import","pass","None","break","except","in","raise","True","class","def"]#and so on

def fontify(self,self_text):
    self.tag_remove('keyword', '1.0', "end")

    for word in keywords:
        idx = '1.0'
        while idx:
            idx = self.search(word, idx, nocase=0, stopindex="end")
            if idx:
                lastidx = '%s+%dc' % (idx, len(word))
                self.tag_add('keyword', idx, lastidx)
                idx = lastidx

    self.tag_config('keyword', foreground='deeppink')

running This Gives me desired output

But how to remove these undesired colored ones

1

There are 1 best solutions below

0
On

This Helped Me
idx = self.search(word, idx,forwards=0,backwards=0,stopindex="end")

The argument forwards means to accept characters forward in search.
The backwards argument is just opposite.
Making them false helped me
Thanks