Configure Entry Text color for only 1 character in Tkinter

Question:

I am making a project in which I created a tkinter window, and in it there is an Entry widget. I need to change the color of the following Entry widget. The following is what I did.

self.input_entry.config(fg="red")

input_entry is the Entry widget.

This changes the color of the entire string. Now, I want to only change the color of a specific character in the string. How do I accomplish this?

I tried getting the specific index of the input entry, but obviously, it didn’t work. Do I need to get the text with self.input_entry.get() and then modify it?

I do not know, can someone inform me of a possible method of doing this?

Asked By: fibonacci_ostrich

||

Answers:

You cannot change the color of individual characters in an Entry widget. You can use a one-line Text widget instead, which allows you to apply tags to a range of characters, and then apply various attributes (such as color) to those tags.

Answered By: Bryan Oakley

Like Bryan said you cannot change the color in a Entry widget.
You can use a Text widget instead and apply tags.

import tkinter as tk
import tkinter.font as tkFont

class App():
    def __init__(self, root):
        self.root = root
        self.font_1 = tkFont.Font(family='', size=16, weight='bold')
        self.t = tk.Text(self.root, width=20, height=1, font=self.font_1, bg="grey30", fg="grey80")
        self.t.pack()
        self.t.insert("1.0", "Hello World! Don't mind")
        self.b = tk.Button(self.root, text="Color", command=self.cb_exp)
        self.b.pack()
        
    def add_tag(self, tagName, index_1, index_2=None):
        """Assign tag to a given index"""        
        self.t.tag_add(tagName, index_1, index_2)

    def change_color(self, tagName, color):
        """First time you configure a tag it will be 'created'"""
        self.t.tag_configure(tagName, foreground=color)
        
    def cb_exp(self):
        """Dummy method"""
        self.change_color("my_lime", "lime")          #name a tag
        self.change_color("my_cyan", "cyan")
        self.change_color("my_yellow", "yellow")
        
        #Add tag 
        self.add_tag("my_lime", 1.1)                #color one character
        self.add_tag("my_cyan", 1.9)
        
        #Add tag to a range
        self.add_tag("my_yellow", "1.13", "1.18")    #color a range
        
                                                    
if __name__ == "__main__":
    root = tk.Tk()
    app = App(root)
    root.mainloop()
Answered By: Module_art
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.