Adding colored text to selected text - Tkinter
I am currently trying to write a program that adds colored text to both sides of the selected text in Tkinter.
What I have managed to do so far is to add text on both sides of the selected text, here is the function I am using:
def addTerm(self):
self.txt.insert(tk.SEL_FIRST,'\\term{')
self.txt.insert(tk.SEL_LAST,'}' )
So, if I have a WORD and I select it, after calling this function it becomes \ Term {WORD}. I am wondering if there is a way to change the color of the text that I am adding, so that when I use the function for the selected text, it adds '\ term {' and '}', which for example are red, but it does not change the color of the text between them.
source to share
Add a tag for the surrounding text:
tk.SEL_FIRST + '-6c', tk.SEL_FIRST # for \term{
tk.SEL_LAST, tk.SEL_LAST + '+1c' # for }
Set color with Text.tag_config(tag_name, background=...)
In the following example, I used term
as the tag name:
try:
import Tkinter as tk
except ImportError:
import tkinter as tk
class MyFrame(tk.Frame):
def __init__(self, master):
tk.Frame.__init__(self, master)
self.txt = tk.Text(self)
self.txt.pack()
self.txt.insert(0.0, 'hello\nworld')
self.btn = tk.Button(self, text='add_term', command=self.add_term)
self.btn.pack()
self.txt.tag_config('term', background='red')
def add_term(self):
self.txt.insert(tk.SEL_FIRST,'\\term{')
self.txt.insert(tk.SEL_LAST,'}' )
self.txt.tag_add('term', tk.SEL_FIRST + '-6c', tk.SEL_FIRST)
self.txt.tag_add('term', tk.SEL_LAST, tk.SEL_LAST + '+1c')
root = tk.Tk()
f = MyFrame(root)
f.pack()
root.mainloop()
UPDATE
Instead of adding the tag after that, you can specify the tag name when calling insert
:
def add_term(self):
self.txt.insert(tk.SEL_FIRST, '\\term{', 'term')
self.txt.insert(tk.SEL_LAST, '}', 'term')
source to share
When you insert text, you can give it the name of the tag or tags that will be applied to the text when you insert it:
def addTerm(self):
self.txt.insert(tk.SEL_FIRST,'\\term{',("markup",))
self.txt.insert(tk.SEL_LAST,'}', ("markup",))
Then you need to configure the tag to have the required attributes. This can be done when you first create the text widget:
self.txt.tag_configure("markup", foreground="gray")
source to share
Someone answered here somehow: How do I change the color of certain words in a tkinter text widget?
You need to add tag
to the function init
:
self.txt.tag_configure("COLOR", foreground="red")
And you can color it like this:
self.text.tag_add("COLOR", 1.0 , "sel.first")
self.text.tag_add("COLOR", "sel.last", "end")
source to share