如何在 python tkinter 中为 *、# 等符号设置自定义颜色

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

如何为某些符号设置特定颜色,例如 、# 等 ' 例如,如果我输入“”,它的颜色应该是蓝色,其他颜色保持不变。

typedecker 先生,我像这样绑定你的功能,但这不起作用


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()

可以遵循与我在单词 中所遵循的相同过程,唯一的变化是用于检测符号的正则表达式。

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

具有必要更改的完整 check_for_symbols 函数将类似于 -:

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