# How to highlight text in a tkinter Text widget?

TkinterServer Side ProgrammingProgramming

Tkinter Text widget is used to create text fields that accept multiline user inputs. Let us suppose that in a text widget, we want to highlight some text. In order to highlight a specific text written in the text widget, tkinter provides the tag_add(tag, i,j) method. It adds tags to the specific text by defining the indexes, i and j.

## Example

In this example, we will create a window application that contains some text and a button which can be triggered to highlight the text.

#Import tkinter library
from tkinter import *
#Create an instance of tkinter frame
win= Tk()
win.geometry("750x450")
#Define a function to highlight the text
text.tag_config("start", background= "black", foreground= "white")
#Create a Tex Field
text= Text(win);
text.insert(INSERT, "Hey there! Howdy?")
text.pack()
#Create a Button to highlight text
Button(win, text= "Highlight", command= add_highlighter).pack()
win.mainloop()

## Output

Running the above code will display a window that contain a button and a text in it.

Now, click the "Highlight" button to highlight the text "Howdy?"

Published on 16-Apr-2021 06:50:20