Reputation: 15226
First I would like to say I am not looking to take spacific words and change all words related to that tag. I am trying to do something akin to highlighting text in word and just changing the text color.
I have a program that will output the string stored in a dictionary by calling the key. I want to change sections of text color within the string but not necessarily all the iterations of that text.
I don't think tagging words would do the job for me as it would take a lot of time to define all the different words I want to change the color of and I do not want all words to be changed. If it is possible to highlight the words and click a button to color the text as well as when I save the text to the library the text retains its color given. That is more along the lines of what I am trying to do.
Further more if it is possible to create some kind of rule that looks for a set of characters and then takes everything inside those characters and changes the color.
Could I write something that would read the data inside the dictionary and look for an identifier lets call it clrGr*
and then look for a closing identifier, lets call it clrGr**
and then any text or string inside the identifiers would have been changed to green. by calling a tag or something similar.
clrGr* Just random string of text between the identifiers clrGr**
What I get currently only lets me change all the color of the text.
Now what I want to do is have something like the following display in my tkinter text box.
Upvotes: 0
Views: 1334
Reputation: 385900
The text widget supports finding ranges of text specified by a regular expression.
Note: the expression must follow tcl regular expression syntax, which has some slight differences from python regular expressions.
For example:
import tkinter as tk
root = tk.Tk()
text = tk.Text(root)
text.pack(fill="both", expand=True)
text.tag_configure("highlight", foreground="green")
text.insert("1.0", '''
blah blah
blah clrGr* Just random string of text between the identifiers clrGr** blah
blah blah
''')
# this just highlights the first match, but you can put this code
# in a loop to highlight the whole file
char_count = tk.IntVar()
index = text.search(r'(?:clrGr\*).*(?:clrGr\*\*)', "1.0", "end", count=char_count, regexp=True)
# we have to adjust the character indexes to skip over the identifiers
if index != "":
start = "%s + 6 chars" % index
end = "%s + %d chars" % (index, char_count.get()-7)
text.tag_add("highlight", start, end)
root.mainloop()
You can, however, call the dump
method on a text widget to get a list of tuples that describe the content of the text widget. You can use this information to either write directly to a file (in a format that only your app will understand), or to convert the data to a known format.
The best description of what the dump
method returns is described in the tcl/tk man pages: http://tcl.tk/man/tcl8.6/TkCmd/text.htm#M108
Upvotes: 1