Adding coloured text to selected text in Tkinter


If we want to implement a text editor in an application that can accept multiline user input, then we can use the Tkinter Text widget. The Text widget in Tkinter is generally used to create a text editor for an application, where we can write text and perform operations like selecting, editing and creating a specific text in the application.

If you want to highlight a text and provide a color to the highlighted text, then you can use the tag_add("start", "first", "second") method. The tag_add() method takes two arguments for selecting the specified text from the text widget. You can give a background color to the highlighted text by configuring the tags using tag_configure() method.


# Import the required library
from tkinter import *

# Create an instance of tkinter frame or window
win = Tk()

# set the size of the window

# Create a new frame
frame= Frame(win)

# Add a text widget
text= Text(frame)

# insert a new text
text.insert(INSERT, "Hello, Welcome to")

# Add a tag to the specified text
text.tag_add("start", "1.8", "1.35")
text.tag_configure("start", background= "black", foreground= "yellow")



Running the above code will display a text widget with some highlighted text.

Updated on 16-Dec-2021 10:42:46