How to highlight the current line of a Text widget in Tkinter?


We can use the Tkinter text widget to accept multiline user input. We can insert text, display information, and get the output from the text widget.

To highlight the currently selected text in a text widget, we can use the tag_add() method that adds a tag in the current text only.

Example

# Import the required library
from tkinter import *

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

# Set the geometry
win.geometry("700x350")

# Add a text widget
text=Text(win, width=80, height=15, font=('Calibri 12'))

# Set default text for text widget
text.insert(INSERT, "Tkinter is a Python Library to create GUI-based applications.")
text.insert(END, "Learning Tkinter is Awesome!!")

# Select Text by adding tags
text.tag_add("start", "1.0","1.7")
text.tag_configure("start", background="OliveDrab1", foreground="black")
text.pack()

win.mainloop()

Output

Running the above code will display a window with a text widget having a highlighted text in it.

Updated on: 05-Aug-2021

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements