Skip to content
Advertisement

How to set custom color for symbols like*,#,etc in python tkinter

How to set specific color for certain symbols like ,#,etc ‘ example if I type “” it’s color should be blue and other stay remain same.

typedecker sir i am binding you function like this but this is not working

from tkinter import*
root = Tk()
def check_for_symbols(symbol_dict) :
    for i in symbol_dict :
        text.tag_remove(i, '1.0', END)
        
        pos = 1.0
        while 1:
            pos = text.search(i, pos, regexp = True, stopindex = END)
            if not pos:
                break
            last_pos = '%s+%dc' % (pos, len(i)) # The only change
            text.tag_add(i, pos, last_pos)
            pos = last_pos
        text.tag_config(i, foreground = symbol_dict[i])
    root.after(1000, lambda:check_for_symbols(symbol_dict))
    return
symbol_dict = {
    "*":"blue"
}
text = Text(root, background = "gray19", foreground = "white", insertbackground = 'white',font="Consolas 15 italic")
text.pack(expand=True,fill=BOTH)
root.after(1000, lambda : check_for_symbols(symbol_dict))
root.mainloop()

Advertisement

Answer

The same procedure as followed in the case of words here by me, can be followed, the only change will be in the regex expression that is to be used to detect the symbols.

last_pos = '%s+%dc' % (pos, len(i)) # The only change

The full check_for_symbols function with the necessary changes in place will look like -:

def check_for_symbols(symbol_dict) : # pass symbol dict as argument using lambda construct.
#    symbol dict format-: {keyword : color}
    
    for i in symbol_dict :
        text.tag_remove(i, '1.0', tk.END)
        
        pos = 1.0
        while 1:
            pos = text.search(i, pos, regexp = True, stopindex = tk.END)
            if not pos:
                break
            last_pos = '%s+%dc' % (pos, len(i)) # The only change
            text.tag_add(i, pos, last_pos)
            pos = last_pos
        text.tag_config(i, foreground = symbol_dict[i])
    root.after(1000, check_for_symbols)
    return
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement