Reputation: 353
I'm making a concordance tool and I want to highlight all the result with colors. In the code below, it only works for line one. The tag will break when there is a new line. For example, when I search for the word 'python' in the string below, the tag only highlight the first line. It does not work for the second and the third line. Please, help me.
import tkinter as tk
from tkinter import ttk
import re
# ==========================
strings="""blah blah blah python blah blah blah
blah blah blah python blah blah blah
blah blah blah python blah blah blah
"""
# ==========================
class Application(tk.Frame):
def __init__(self, master=None):
super().__init__(master)
self.pack()
self.create_widget()
def create_widget(self):
self.word_entry=ttk.Entry(self)
self.word_entry.pack()
self.word_entry.bind('<Return>', self.concord)
self.string_text=tk.Text(self)
self.string_text.insert(tk.INSERT, strings)
self.string_text.pack()
# ==========================
def concord(self, event):
word_concord=re.finditer(self.word_entry.get(), self.string_text.get(1.0, tk.END))
for word_found in word_concord:
self.string_text.tag_add('color', '1.'+str(word_found.start()), '1.'+str(word_found.end()))
self.string_text.tag_config('color', background='yellow')
# ==========================
def main():
root=tk.Tk()
myApp=Application(master=root)
myApp.mainloop()
if __name__=='__main__':
main()
Upvotes: 1
Views: 3764
Reputation: 386020
Every index you use to add highlighting begins with "1.", so it's always only going to highlight the first sentence. For example, if the line is 36 characters long, an index of "1.100" will be treated exactly the same as "1.36".
Tkinter can compute new indexes by adding to an existing index, so instead of "1.52" (for a line that is 36 characters long) you want "1.0+52chars". For example:
def concord(self, event):
...
for word_found in word_concord:
start = self.string_text.index("1.0+%d chars" % word_found.start())
end = self.string_text.index("1.0+%d chars" % word_found.end())
self.string_text.tag_add('color', start, end)
...
Upvotes: 2