Reputation: 181
I'm building a program which highlights certain words in the text widget as the user writes them.
Everything is working so far except that the program keeps highlighting words within words, and I don't know how to make it not do that.
from tkinter import *
root = Tk()
frame = Frame(root)
frame.grid(row=0, column=0, sticky="nsew")
root.grid_rowconfigure(0, weight=1)
root.grid_columnconfigure(0, weight=1)
textbox = Text(frame,width=100, height=10)
textbox.grid(row=1, column=7, columnspan=10)
textbox.tag_config("vegetables", foreground='green')
textbox.tag_config("fruits", foreground='red')
def search(textbox, keyword, tag):
pos = '1.0'
while True:
idx = textbox.search(keyword, pos, END, nocase=True)
if not idx:
break
pos = '{}+{}c'.format(idx, len(keyword))
textbox.tag_add(tag, idx, pos)
def search2(event):
for word in vegetables:
search(textbox, word, "vegetables")
for word in fruits:
search(textbox, ordet, "fruits")
textbox.bind("<space>", search2)
frame.mainloop()
I'm using "vegetables" and "fruits" as examples here to make the function of the program more intuitive.
The problem I'm trying to fix can be illustrated by the following sentence, which shows how the program identifies a vegetable within another word which means something else:
"All I want is peace on earth"
Any help is appreciated!
Upvotes: 0
Views: 85
Reputation: 782148
Add the regexp=True
option and use \y
to match word boundaries.
def search(textbox, keyword, tag):
pos = '1.0'
while True:
idx = textbox.search(fr'\y{keyword}\y', pos, END, nocase=True, regexp=True)
if not idx:
break
pos = '{}+{}c'.format(idx, len(keyword))
textbox.tag_add(tag, idx, pos)
Upvotes: 2