Search code examples
python-3.xtkinterwidgetforegroundtkinter-entry

Tkinter - How to use option 'foreground' for some text in Entry widget?


Here is my code:

from tkinter import *
root = Tk()
root.title("Punctured Convolution Encoder dan Viterbi Decoder")
root.geometry("1350x655+0+0")

frame_input = LabelFrame(root, text="Input")
frame_input.place(x=20, y=10, width=400, height=200)

# input#
lbl_in = Label(frame_input, text="Input", font=("Arial", 16))
lbl_in.place(x=10, y=20)
bin_in = Entry(frame_input, font=('Gill Sans MT', 16))
bin_in.place(x=130, y=20, width=240)

def klik_proses():
    bin_in.selection_range(1,2)
    bin_in.config(foreground="red")
    bin_in.selection_range(4,5)
    bin_in.config(foreground="red")

btn_proses = Button(frame_input, text="test", width=12, command=klik_proses)
btn_proses.place(x=140, y=100)

root.mainloop()

The result is the color of the whole text in entry widget was changed, when I pressed the button. How can I change color for some text in the entry widget?

e.g: I enter 123456789 in the entry box, then I want to change text color for number 2 and 5. So, there are 2 numbers have red color and the others have black color.


Solution

  • It is not possible to change the color of only part of the text in an Entry, but it is possible in a Text widget using tags. So I suggest you to create a one line Text widget.

    Here is an example:

    import tkinter as tk
    
    def change_color():
        entry.tag_add('red', '1.1')
        entry.tag_add('red', '1.4')
    
    root = tk.Tk()
    
    entry = tk.Text(root, height=1, width=20)
    entry.tag_configure('red', foreground='red') 
    entry.bind('<Return>', lambda e: "break")  # prevent newlines
    entry.insert('1.0', '123456789')
    
    entry.pack()
    tk.Button(root, text='Change color', command=change_color).pack()
    root.mainloop()
    

    You can find more information about the Text widget on this website .