0

this is my first question here... Im doing a project that highlight words entered in a list How i can highlight it? my code:

   import tkinter
   root = tkinter.Tk()
   words = ["Potatos","Tomatoes","Carrots"]
   box = tkinter.Text(root)
   box.pack()
   root.mainloop()

How i can highlight the text of a color if i enter a word that is in the words list? im sorry if i sound stupid but im a novice

  • here is a similar question: https://stackoverflow.com/questions/14786507/how-to-change-the-color-of-certain-words-in-the-tkinter-text-widget/30339009 – JacksonPro Dec 12 '20 at 02:54
  • Does this answer your question? [How to highlight text in a tkinter Text widget](https://stackoverflow.com/questions/3781670/how-to-highlight-text-in-a-tkinter-text-widget) – acw1668 Dec 12 '20 at 08:40

1 Answers1

0

Try this:

  • Add highlight_text() function.
  • Add clear() function.
  • Add Button for highlight.
  • Add Button for clear.
  • Remove brace bracket that you don't needed List

Modified code:

import tkinter
root = tkinter.Tk()

def highlight_text():
    try:
        box.tag_add("start", "sel.first", "sel.last")        
    except tk.TclError:
        pass

def clear():
    box.tag_remove("start",  "1.0", 'end')
       
words = "Potatos","Tomatoes","Carrots"
        
box = tkinter.Text(root, width=25, height=5)
box.insert(tkinter.INSERT, words)
box.pack()
box.tag_configure("start", background="black", foreground="red")

highlight_btn = tkinter.Button(root, text="Highlight", command=highlight_text)
highlight_btn.pack(side=tkinter.LEFT)
       
clear_btn = tkinter.Button(root, text="Clear", command=clear)
clear_btn.pack(side=tkinter.LEFT)

root.mainloop()

Output before, highlight and clear:

enter image description here enter image description here enter image description here

toyota Supra
  • 3,181
  • 4
  • 15
  • 19