How to avoid changing colour of selected text in tkinter when I highlight syntax with idlelib

Question:

I have recently found out how to highlight syntax in tkinter text widget using idlelib. I’ve tried it and I thought it would be cool to use that to make my text editor app. But the problem is that the text which is coloured by the filter doesn’t work when the text is selected by the user. This below is a small example of what I am trying to achieve:

from tkinter import *
from idlelib.colorizer import ColorDelegator
from idlelib.percolator import Percolator

root = Tk()

txt = Text(root, font=("Courier", 20))
txt.pack()

cdg = ColorDelegator()

cdg.tagdefs['COMMENT'] = {'foreground': '#FF0000', 'background': '#FFFFFF'}
cdg.tagdefs['KEYWORD'] = {'foreground': '#007F00', 'background': '#FFFFFF'}
cdg.tagdefs['BUILTIN'] = {'foreground': '#7F7F00', 'background': '#FFFFFF'}
cdg.tagdefs['STRING'] = {'foreground': '#7F3F00', 'background': '#FFFFFF'}
cdg.tagdefs['DEFINITION'] = {'foreground': '#007F7F', 'background': '#FFFFFF'}

Percolator(txt).insertfilter(cdg)

root.mainloop()

Expected Result (Just a screenshot from the IDE I am using, I want the colour to still be visible when its selected):

enter image description here

Actual Result (You can see that the selected text ‘t ("Hello Wor’ is black but I don’t want it to be black, I want it to be what it is):

enter image description here

So my aim is to NOT change the foreground colour of the selected text regardless of what colour it is tagged with. Thanks in advance.

Asked By: ss3387

||

Answers:

So OP is right. ColorDelegator calls self.tag_raise('sel') which puts the tag at the top so the foreground option of the "sel" tag is taken instead of the other tags.

If you do this:

import tkinter as tk

root = tk.Tk()
txt = tk.Text(root)
txt.pack()
print(txt.tag_config("sel")["foreground"]) # Outputs ('foreground', '', '', '', '#000000')

You can see that tkinter or tcl has set a default foreground option for the "sel" tag. To remove it use txt.tag_config("sel", foreground="").

Answered By: TheLizzard