Highlight color for a specific line of text based on a keyword in Tkinter


Creating effective GUIs often involves displaying and manipulating text. Tkinter, the popular Python GUI toolkit, provides a versatile Text widget for handling text-based content. In this tutorial, we will show how you can highlight specific lines of text based on certain criteria in a Tkinter application.

Setting up the Tkinter Environment

Let's begin by setting up a basic Tkinter environment. Ensure Tkinter is installed by running −

pip install tk

Creating a Simple Tkinter Window

Now, let's create a simple Tkinter window with a Text widget −

import tkinter as tk

# Create the Tkinter window
root = tk.Tk()
root.title("Highlighting colour for a specific line of text")
root.geometry("720x250")

# Create a Text widget
text_widget = tk.Text(root, wrap=tk.WORD)
text_widget.pack(expand=True, fill=tk.BOTH)

# Start the Tkinter event loop
root.mainloop()

This forms the foundation for our text highlighting demonstration.

Text Highlighting in Tkinter

To highlight specific lines based on a keyword, we'll create a function named highlight_keyword. This function will interact with the Text widget, applying tags to relevant portions of text −

def highlight_keyword(text_widget, keyword, line_number, fg_color='yellow', bg_color='red'):
   start_index = text_widget.index(f'{line_number}.0')
   end_index = text_widget.index(f'{line_number + 1}.0')
   line_text = text_widget.get(start_index, end_index)

   if keyword in line_text:
      start_index = start_index + '+%dc' % line_text.index(keyword)
      end_index = start_index + '+%dc' % len(keyword)
      text_widget.tag_add('highlight', start_index, end_index)
      text_widget.tag_config('highlight', foreground=fg_color, background=bg_color)

Breaking down the highlight_keyword function

  • Determine Line Indices − Obtain the start and end indices of the specified line within the Text widget.

  • Retrieve Line Text − Extract the text content of the specified line.

  • Check for Keyword Existence − Verify if the keyword is present in the line.

  • Apply Tag − If the keyword is found, calculate the indices for the keyword within the line and apply a tag ('highlight') to that range.

  • Configure Tag Styling − Customize the appearance of the tag, specifying foreground and background colors.

Incorporating text insertion and keyword highlighting in Tkinter

Now, let's incorporate text insertion and keyword highlighting into our Tkinter environment −

# Insert some text into the Text widget
text_widget.insert(tk.END, "This is the first line.\n")
text_widget.insert(tk.END, "This line contains the keyword.\n")
text_widget.insert(tk.END, "This is the third line.\n")
text_widget.insert(tk.END, "This is the fourth line.\n")
text_widget.insert(tk.END, "This is the fifth line.\n")
text_widget.insert(tk.END, "This is the sixth line.\n")

# Highlight the line containing the keyword
highlight_keyword(text_widget, 'keyword', 2)

Putting It All Together

Let’s put all these together and check the output −

Example

import tkinter as tk

def highlight_keyword(
      text_widget, keyword, line_number, 
      fg_color='yellow', bg_color='red'):
   start_index = text_widget.index(f'{line_number}.0')
   end_index = text_widget.index(f'{line_number + 1}.0')
   line_text = text_widget.get(start_index, end_index)

   if keyword in line_text:
      start_index = start_index + '+%dc' % line_text.index(keyword)
      end_index = start_index + '+%dc' % len(keyword)
      text_widget.tag_add('highlight', start_index, end_index)
      text_widget.tag_config(
         'highlight', foreground=fg_color, 
         background=bg_color
      )

# Create the Tkinter window
root = tk.Tk()
root.title("Highlighting colour for a specific line of text")
root.geometry("720x250")

# Create a Text widget
text_widget = tk.Text(root, wrap=tk.WORD)
text_widget.pack(expand=True, fill=tk.BOTH)

# Insert some text into the Text widget
text_widget.insert(tk.END, "This is the first line.\n")
text_widget.insert(tk.END, "This line contains the keyword.\n")
text_widget.insert(tk.END, "This is the third line.\n")
text_widget.insert(tk.END, "This is the fourth line.\n")
text_widget.insert(tk.END, "This is the fifth line.\n")
text_widget.insert(tk.END, "This is the sixth line.\n")

# Highlight the line containing the keyword
highlight_keyword(text_widget, 'keyword', 2)

# Start the Tkinter event loop
root.mainloop()

Here, six lines of text are inserted into the Text widget. The highlight_keyword function is then called to highlight the line containing the keyword 'keyword.'

Output

On running this code, you will get the following output window −

Conclusion

Text highlighting in Tkinter enhances the usability of graphical applications. Using the Text widget and tagging mechanism allows developers to implement dynamic and visually appealing text highlighting based on various criteria.

Updated on: 15-Feb-2024

1 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements