Skip to content
Related Articles

Related Articles

Improve Article

Change the color of certain words in the tkinter text widget

  • Last Updated : 01 Aug, 2020

Python has various options for Graphical User Interface (GUI) development. One of the options is Tkinter. Tkinter and Python together provide a faster way for GUI development. The Tk GUI toolkit provides an object-oriented interface.

For creating GUI applications using Tkinter we have to follow a few steps –

  • Import Tkinter module.
  • Create the main window.
  • Add various widgets to the GUI application as per requirements.
  • Main event loop for every trigger by the user for performing specific actions.

Text widgets have advanced options for editing a text with multiple lines and format the display settings of that text example font, text color, background color. We can also use tabs and marks for locating and editing sections of data. We can also use images in the text and insert borders as well. And everything can be formatted as per the requirements.
 

Syntax : Text ( master, option, … )

Parameters : master represents parent window and option represents various widget options. They can be given as key-value pairs separated by commas.



Return : Return a Text object. 
 

Example 1 : In first example we will add a tag to a section of text by specifying the indices and highlight the selected text. Here, we are using tag_add and tag_config.
 

Python3




# import all functions from the tkinter
from tkinter import *
  
# Create a GUI window  
root = Tk()
  
# Create a text area box   
# for filling or typing the information.
text = Text(root)
  
# insert given string in text area
text.insert(INSERT, "Hello, everyone!\n")
  
text.insert(END, "This is 2020.\n")
  
text.insert(END, "Pandemic has resulted 
             in economic slowdown worldwide")
  
text.pack(expand=1, fill=BOTH)
  
# add tag using indices for the
# part of text to be highlighted
text.tag_add("start", "2.8", "1.13")
  
#configuring a tag called start
text.tag_config("start", background="black",
                 foreground="red")
  
# start the GUI
root.mainloop()

Output : 
 

Example 2 : In this example, user can highlight text as per their wish by selecting the text to be highlighted. Here, we are using tag_configure and tag_add. 
 

Python3




# import all functions from the tkinter   
import tkinter as tk
from tkinter.font import Font
  
# create a Pad class
class Pad(tk.Frame):
  
    # constructor to add buttons and text to the window
    def __init__(self, parent, *args, **kwargs):
        tk.Frame.__init__(self, parent, *args, **kwargs)
  
        self.toolbar = tk.Frame(self, bg="#eee")
        self.toolbar.pack(side="top", fill="x")
          
        # this will add Highlight button in the window
        self.bold_btn = tk.Button(self.toolbar, text="Highlight",
                                  command=self.highlight_text)
        self.bold_btn.pack(side="left")
  
        # this will add Clear button in the window
        self.clear_btn = tk.Button(self.toolbar, text="Clear",
                                   command=self.clear)
        self.clear_btn.pack(side="left")
  
        # adding the text 
        self.text = tk.Text(self)
        self.text.insert("end", "Pandemic has resulted in economic slowdown worldwide")
        self.text.focus()
        self.text.pack(fill="both", expand=True)
          
        #configuring a tag called start
        self.text.tag_configure("start", background="black", foreground="red")
  
    # method to highlight the selected text
    def highlight_text(self):
          
        # if no text is selected then tk.TclError exception occurs
        try:
            self.text.tag_add("start", "sel.first", "sel.last")        
        except tk.TclError:
            pass
  
    # method to clear all contents from text widget.
    def clear(self):
        self.text.tag_remove("start""1.0", 'end')
  
# function
def demo():
  
    # Create a GUI window 
    root = tk.Tk()
  
    # place Pad object in the root window
    Pad(root).pack(expand=1, fill="both")
  
    # start the GUI
    root.mainloop()
  
# Driver code
if __name__ == "__main__":
  
    # function calling
    demo()

Output :



Before selecting the text and hitting the highlight button :

After selecting the text and hitting the highlight button :

 

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course




My Personal Notes arrow_drop_up
Recommended Articles
Page :