I want to make like an ide in tkinter and i want to color some certain words like "on" or "start" how can i do this?
-
I think this discusses your question.– RoryMay 24 at 12:59
1 Answer
You need to show us what you have tried so far. Do share your current code, that would improve the question a lot.
Solution
The simplest solution, is to use the classes from idle itself, you can import the idlelib library.
In the following example, we are using idlelib's Percolator and ColorDelegator classes. The ColorDelegator provides all token respective colors and basically does all you need as per the question.
import tkinter as tk
from idlelib.percolator import Percolator
from idlelib.colorizer import ColorDelegator
main = tk.Tk()
text = tk.Text(main)
text.pack()
Percolator(text).insertfilter(ColorDelegator())
main.mainloop()
Reference
From scratch
The above solution makes use of the idlelib classes. Using them like this may show some performance issues under various operating systems. So then you can go implementing the highlighting all by yourself.
tkinter's Text widget have the tags feature. You can use the tag_add(tag, start, end)
function to add a specific tag to the text ranging from start
to end
. The start, end parameters should be Text widget indices.
...
text.insert('1.0', "lorem ipsum dolor sit amet something something...")
# configures a tag named 'foo' to have red foreground color
text.tag_configure('foo', foreground='red')
# add the tag from 1.0 to 1.6 manually.
text.tag_add('foo', '1.0', '1.6')
...
The result will be as following:
Searching for words
You can use the builtin text.search
method to search for specific terms in the text widget. This will return the indices, which are enough to highlight the term!
- This question have been answered a lot of times on stackoverflow, see bryan oakley's answer to syntax highlighting on a text widget.
- For triggering the highlight event efficiently, see this answer