Примерно так, а дальше сами.
from tkinter import Tk, Text, END, INSERT, Label, CURRENT
class Application(Tk):
def __init__(self):
super().__init__()
self.widget_text = Text(self)
self.widget_text.pack(expand=True)
self.configure_key_words()
self.widget_text.bind("<KeyPress>", self.handler)
def get_last_line(self):
full_text = self.widget_text.get("1.0", END)
list_string = full_text.split('\n')[::-1]
last_line = list_string[1]
return last_line
def get_last_word(self):
last_word = self.get_last_line().split(' ')[-1]
return last_word
def configure_key_words(self):
self.widget_text.tag_config('apple', foreground='red', underline=1,
font=("Arial", 12, 'bold'))
self.widget_text.tag_config('banana', foreground='green',
font=("Arial", 12, 'bold'))
def handler(self, event):
last_word = self.get_last_word()
if event.char == ' ' or '\n':
line, _ = self.widget_text.index(CURRENT).split(".")
word_start_position = self.get_last_line().rfind(last_word)
match last_word:
case "яблоко":
print(line, word_start_position)
self.widget_text.delete(f"{line}.{word_start_position}", END)
self.widget_text.insert(f"{line}.{word_start_position}", 'яблоко', 'apple')
case "банан":
print(line, word_start_position)
self.widget_text.delete(f"{line}.{word_start_position}", END)
self.widget_text.insert(f"{line}.{word_start_position}", 'банан', 'banana')
def main():
Application().mainloop()
if __name__ == '__main__':
main()