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
JavaScript
x
25
25
1
from tkinter import*
2
root = Tk()
3
def check_for_symbols(symbol_dict) :
4
for i in symbol_dict :
5
text.tag_remove(i, '1.0', END)
6
7
pos = 1.0
8
while 1:
9
pos = text.search(i, pos, regexp = True, stopindex = END)
10
if not pos:
11
break
12
last_pos = '%s+%dc' % (pos, len(i)) # The only change
13
text.tag_add(i, pos, last_pos)
14
pos = last_pos
15
text.tag_config(i, foreground = symbol_dict[i])
16
root.after(1000, lambda:check_for_symbols(symbol_dict))
17
return
18
symbol_dict = {
19
"*":"blue"
20
}
21
text = Text(root, background = "gray19", foreground = "white", insertbackground = 'white',font="Consolas 15 italic")
22
text.pack(expand=True,fill=BOTH)
23
root.after(1000, lambda : check_for_symbols(symbol_dict))
24
root.mainloop()
25
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.
JavaScript
1
2
1
last_pos = '%s+%dc' % (pos, len(i)) # The only change
2
The full check_for_symbols
function with the necessary changes in place will look like -:
JavaScript
1
18
18
1
def check_for_symbols(symbol_dict) : # pass symbol dict as argument using lambda construct.
2
# symbol dict format-: {keyword : color}
3
4
for i in symbol_dict :
5
text.tag_remove(i, '1.0', tk.END)
6
7
pos = 1.0
8
while 1:
9
pos = text.search(i, pos, regexp = True, stopindex = tk.END)
10
if not pos:
11
break
12
last_pos = '%s+%dc' % (pos, len(i)) # The only change
13
text.tag_add(i, pos, last_pos)
14
pos = last_pos
15
text.tag_config(i, foreground = symbol_dict[i])
16
root.after(1000, check_for_symbols)
17
return
18