How to highlight text in a tkinter Text widget?

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.


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()
#Define a function to highlight the text
def add_highlighter():
   text.tag_add("start", "1.11","1.17")
   text.tag_config("start", background= "black", foreground= "white")
#Create a Tex Field
text= Text(win);
text.insert(INSERT, "Hey there! Howdy?")
#Create a Button to highlight text
Button(win, text= "Highlight", command= add_highlighter).pack()


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?"

Updated on: 16-Apr-2021

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started