Home » Tutorials » How to Change Text Color and Style in Python

How to Change Text Color and Style in Python

Are you ready to spice up your Python projects with some visual flair? Starting with text customization is a perfect choice. Whether you’re crafting a brand-new application or refreshing one you’ve already developed, changing the color and style of your text can have a dramatic impact.

In today’s tutorial, you’ll learn how to use Python to customize the look of text by adjusting colors, styles, and more. We’ll be using a user-friendly graphical interface (GUI) built with tkinter, making it easy and intuitive to make these changes. So, let’s dive in and start making your text stand out!

Table of Contents

Necessary Libraries

We need a graphical user interface (GUI) so make sure to install the tkinter library via the terminal or your command prompt:

$ pip install tk 

Imports

We begin by importing the tkinter library and alias it as tk to simplify referencing its components when creating a graphical user interface. Additionally, from this library, we import ttk to utilize themed tkinter widgets, and font to manage fonts.

import tkinter as tk
from tkinter import ttk, font

Color and Style Definitions

Next, we create a colors dictionary that maps color names to their hexadecimal representations. We then copy this dictionary to another dictionary called backgrounds to store background colors, ensuring that the background colors are identical to those defined in the original dictionary.

Following this, we define a list named styles that includes options such as ‘Normal’, ‘Bold’, ‘Italic’, and ‘Bold/Italic’ for users to choose their text style. Lastly, we introduce lists for brightness_levels and effects, enabling users to customize these aspects with options like ‘Dim’, ‘Normal’, ‘Bright’ for brightness, and ‘None’, ‘Underline’ for effects.

# Define color options
colors = {
   "Black": "#000000", "Red": "#FF0000", "Green": "#00FF00", "Yellow": "#FFFF00",
   "Blue": "#0000FF", "Magenta": "#FF00FF", "Cyan": "#00FFFF", "White": "#FFFFFF"
}
backgrounds = colors.copy()  # Background colors use the same values
styles = ["Normal", "Bold", "Italic", "Bold/Italic"]
effects = ["None", "Underline"]
brightness_levels = ["Dim", "Normal", "Bright"]

Defining the ColorTextApp Class

Here we start by creating a class named ColorTextApp that inherits from tkinter, allowing it to utilize properties of the tkinter library such as creating a main window. In the __init__ function, we set up our main window upon its creation. We use super().__init__() to ensure that our main window inherits all necessary properties from tkinter properly.

Next, we set a title for our main window and define its geometry, including the default size and font for the text. Finally, we use the setup_ui method to establish the user interface.

class ColorTextApp(tk.Tk):
   def __init__(self):
       super().__init__()
       self.title("Color Text App - The Pycodes")
       self.geometry("600x500")
       self.current_font = font.Font(family="Arial", size=12)  # Default font
       self.setup_ui()

Setup_ui Method

In this part, we will set up the GUI elements that allow the user to interact with the main window. We start by creating an entry box for the user to input their text. Next, we will use a StringVar() to ensure that the fore_color_var can store text. Then we create a label that says ‘Foreground Color’ and place it using the grid layout to inform the user. After this, we introduce a drop-down list that contains a dictionary of colors using ttk.Combobox() and link it to the fore_color_var. We repeat a similar process for the background color, text style, effect, and brightness.

Finally, we create a button named ‘Apply and Display’ that triggers the apply_colors() function. We also set up a text widget (display_text) with specific height, width, and font to display the result. All of these elements will be placed on the main window using the grid layout.

   def setup_ui(self):
       self.text_entry = ttk.Entry(self, width=50)
       self.text_entry.grid(row=0, column=1, padx=10, pady=10)


       self.fore_color_var = tk.StringVar()
       ttk.Label(self, text="Foreground Color:").grid(row=1, column=0, padx=10, pady=5)
       self.fore_color_dropdown = ttk.Combobox(self, textvariable=self.fore_color_var, values=list(colors.keys()))
       self.fore_color_dropdown.grid(row=1, column=1, padx=10, pady=5)


       self.back_color_var = tk.StringVar()
       ttk.Label(self, text="Background Color:").grid(row=2, column=0, padx=10, pady=5)
       self.back_color_dropdown = ttk.Combobox(self, textvariable=self.back_color_var, values=list(backgrounds.keys()))
       self.back_color_dropdown.grid(row=2, column=1, padx=10, pady=5)


       self.style_var = tk.StringVar()
       ttk.Label(self, text="Text Style:").grid(row=3, column=0, padx=10, pady=5)
       self.style_dropdown = ttk.Combobox(self, textvariable=self.style_var, values=styles)
       self.style_dropdown.grid(row=3, column=1, padx=10, pady=5)


       self.effect_var = tk.StringVar()
       ttk.Label(self, text="Text Effect:").grid(row=4, column=0, padx=10, pady=5)
       self.effect_dropdown = ttk.Combobox(self, textvariable=self.effect_var, values=effects)
       self.effect_dropdown.grid(row=4, column=1, padx=10, pady=5)


       self.brightness_var = tk.StringVar()
       ttk.Label(self, text="Brightness:").grid(row=5, column=0, padx=10, pady=5)
       self.brightness_dropdown = ttk.Combobox(self, textvariable=self.brightness_var, values=brightness_levels)
       self.brightness_dropdown.grid(row=5, column=1, padx=10, pady=5)


       self.apply_btn = ttk.Button(self, text="Apply and Display", command=self.apply_colors)
       self.apply_btn.grid(row=6, column=1, padx=10, pady=10)


       # Using a Text widget to display the results instead of a Label
       self.display_text = tk.Text(self, height=10, width=50, font=self.current_font)
       self.display_text.grid(row=7, column=1, padx=10, pady=10)

Defining the apply_colors Function

This function begins by retrieving the user inputs using the get() method, starting with the text and then the foreground and background colors. For these last two, it maps the input color to its hexadecimal value, if available. If not, the text will be displayed in default colors: white for the foreground and black for the background. The function also retrieves the style, brightness, and effect, and applies these to the text using display_text.

The font is updated based on the user’s style and brightness input: ‘bold’ if ‘Bold’ is included in the style, ‘italic’ if ‘Italic’, and the size is adjusted according to the brightness setting. Additionally, if ‘Underline’ is selected as an effect, the text is underlined; otherwise, any underline is removed.

   def apply_colors(self):
       text = self.text_entry.get()
       fore = colors.get(self.fore_color_var.get(), "#FFFFFF")
       back = backgrounds.get(self.back_color_var.get(), "#000000")
       style = self.style_var.get()
       effect = self.effect_var.get()
       brightness = self.brightness_var.get()


       # Update the font based on user input
       weight = "bold" if "Bold" in style else "normal"
       slant = "italic" if "Italic" in style else "roman"
       size = 10 if brightness == "Dim" else 14 if brightness == "Bright" else 12


       self.current_font.config(weight=weight, slant=slant, size=size)
       self.display_text.config(font=self.current_font, fg=fore, bg=back)


       # Clear existing text and insert new styled text
       self.display_text.delete('1.0', tk.END)
       self.display_text.insert(tk.END, text)


       # Apply underline if selected
       if effect == "Underline":
           self.display_text.tag_configure("underline", underline=True)
           self.display_text.tag_add("underline", "1.0", "end")
       else:
           self.display_text.tag_remove("underline", "1.0", "end")

Main Block

This part ensures that the script is run directly and not imported as a module. It also ensures that the main window remains running and responsive to the user until they decide to exit.

if __name__ == "__main__":
   app = ColorTextApp()
   app.mainloop()

Example

Full Code

import tkinter as tk
from tkinter import ttk, font


# Define color options
colors = {
   "Black": "#000000", "Red": "#FF0000", "Green": "#00FF00", "Yellow": "#FFFF00",
   "Blue": "#0000FF", "Magenta": "#FF00FF", "Cyan": "#00FFFF", "White": "#FFFFFF"
}
backgrounds = colors.copy()  # Background colors use the same values
styles = ["Normal", "Bold", "Italic", "Bold/Italic"]
effects = ["None", "Underline"]
brightness_levels = ["Dim", "Normal", "Bright"]


class ColorTextApp(tk.Tk):
   def __init__(self):
       super().__init__()
       self.title("Color Text App - The Pycodes")
       self.geometry("600x500")
       self.current_font = font.Font(family="Arial", size=12)  # Default font
       self.setup_ui()


   def setup_ui(self):
       self.text_entry = ttk.Entry(self, width=50)
       self.text_entry.grid(row=0, column=1, padx=10, pady=10)


       self.fore_color_var = tk.StringVar()
       ttk.Label(self, text="Foreground Color:").grid(row=1, column=0, padx=10, pady=5)
       self.fore_color_dropdown = ttk.Combobox(self, textvariable=self.fore_color_var, values=list(colors.keys()))
       self.fore_color_dropdown.grid(row=1, column=1, padx=10, pady=5)


       self.back_color_var = tk.StringVar()
       ttk.Label(self, text="Background Color:").grid(row=2, column=0, padx=10, pady=5)
       self.back_color_dropdown = ttk.Combobox(self, textvariable=self.back_color_var, values=list(backgrounds.keys()))
       self.back_color_dropdown.grid(row=2, column=1, padx=10, pady=5)


       self.style_var = tk.StringVar()
       ttk.Label(self, text="Text Style:").grid(row=3, column=0, padx=10, pady=5)
       self.style_dropdown = ttk.Combobox(self, textvariable=self.style_var, values=styles)
       self.style_dropdown.grid(row=3, column=1, padx=10, pady=5)


       self.effect_var = tk.StringVar()
       ttk.Label(self, text="Text Effect:").grid(row=4, column=0, padx=10, pady=5)
       self.effect_dropdown = ttk.Combobox(self, textvariable=self.effect_var, values=effects)
       self.effect_dropdown.grid(row=4, column=1, padx=10, pady=5)


       self.brightness_var = tk.StringVar()
       ttk.Label(self, text="Brightness:").grid(row=5, column=0, padx=10, pady=5)
       self.brightness_dropdown = ttk.Combobox(self, textvariable=self.brightness_var, values=brightness_levels)
       self.brightness_dropdown.grid(row=5, column=1, padx=10, pady=5)


       self.apply_btn = ttk.Button(self, text="Apply and Display", command=self.apply_colors)
       self.apply_btn.grid(row=6, column=1, padx=10, pady=10)


       # Using a Text widget to display the results instead of a Label
       self.display_text = tk.Text(self, height=10, width=50, font=self.current_font)
       self.display_text.grid(row=7, column=1, padx=10, pady=10)


   def apply_colors(self):
       text = self.text_entry.get()
       fore = colors.get(self.fore_color_var.get(), "#FFFFFF")
       back = backgrounds.get(self.back_color_var.get(), "#000000")
       style = self.style_var.get()
       effect = self.effect_var.get()
       brightness = self.brightness_var.get()


       # Update the font based on user input
       weight = "bold" if "Bold" in style else "normal"
       slant = "italic" if "Italic" in style else "roman"
       size = 10 if brightness == "Dim" else 14 if brightness == "Bright" else 12


       self.current_font.config(weight=weight, slant=slant, size=size)
       self.display_text.config(font=self.current_font, fg=fore, bg=back)


       # Clear existing text and insert new styled text
       self.display_text.delete('1.0', tk.END)
       self.display_text.insert(tk.END, text)


       # Apply underline if selected
       if effect == "Underline":
           self.display_text.tag_configure("underline", underline=True)
           self.display_text.tag_add("underline", "1.0", "end")
       else:
           self.display_text.tag_remove("underline", "1.0", "end")


if __name__ == "__main__":
   app = ColorTextApp()
   app.mainloop()

Happy Coding!

Subscribe for Top Free Python Tutorials!

Receive the best directly.  Elevate Your Coding Journey!

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top
×