0

I want to highlight the words which are present in a file . I have stored the file in a var called KEYWORDS with the arguments as open("word-lists/keywords").read().split("\n")

this is the code which handles the highlighting(from another stack overflow anwser):

    print("pressed")
    index = text.search(r'\s', "insert", backwards=True, regexp=True)
    if index == "":
        index = "1.0"
    else:
        index = text.index("%s+1c" % index)
    word = text.get(index, "insert")
    if word in KEYWORDS:
        text.tag_add("highlight", index, "%s+%dc" % (index, len(word)))
    else:
        text.tag_remove("highlight", index, "%s+%dc" % (index, len(word)))

and I use this to call this function : text.bind("<Key>", Syntaxhighlight)

the words are being highlighted only if i press the spacebar before typing . i want that it should start from the start.

heres the full code:

win = tkinter.Tk()
text = tkinter.Text(win, font=font, bg=BACKGROUND, fg=FOREGROUND, insertbackground=FOREGROUND, borderwidth=0,
                    highlightthickness=0)
text.pack(expand=True, side=tkinter.TOP, fill=tkinter.BOTH)
text.tag_configure("highlight", foreground=KEYWORD, underline=False)


def Syntaxhighlight(event):
    print("pressed")
    index = text.search(r'\s', "insert", backwards=True, regexp=True)
    if index == "":
        index = "1.0"
    else:
        index = text.index("%s+1c" % index)
    word = text.get(index, "insert")
    if word in KEYWORDS:
        text.tag_add("highlight", index, "%s+%dc" % (index, len(word)))
    else:
        text.tag_remove("highlight", index, "%s+%dc" % (index, len(word)))

text.bind("<Key>", Syntaxhighlight)

win.mainloop()


MrHola21
  • 301
  • 2
  • 8

0 Answers0