python - Changing select sections of text to different colors in a tkinter text box? -


first not looking take spacific words , change words related tag. trying akin highlighting text in word , changing text color.

i have program output string stored in dictionary calling key. want change sections of text color within string not iterations of text.

i don't think tagging words job me take lot of time define different words want change color of , not want words changed. if possible highlight words , click button color text when save text library text retains color given. more along lines of trying do.

further more if possible create kind of rule looks set of characters , takes inside characters , changes color.

could write read data inside dictionary , identifier lets call clrgr* , closing identifier, lets call clrgr** , text or string inside identifiers have been changed green. calling tag or similar.

clrgr* random string of text between identifiers clrgr** 

what lets me change color of text. enter image description here

now want have following display in tkinter text box. enter image description here

applying tags via regular expression

the text widget supports finding ranges of text specified regular expression.

note: expression must follow tcl regular expression syntax, has slight differences python regular expressions.

for example:

import tkinter 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* random string of text between identifiers clrgr** blah blah blah ''')  # highlights first match, can put code # in loop highlight whole file char_count = tk.intvar() index = text.search(r'(?:clrgr\*).*(?:clrgr\*\*)', "1.0", "end", count=char_count, regexp=true)  # have adjust character indexes skip on 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() 

saving color information

you can, however, call dump method on text widget list of tuples describe content of text widget. can use information either write directly file (in format app understand), or convert data known format.

the best description of dump method returns described in tcl/tk man pages: http://tcl.tk/man/tcl8.6/tkcmd/text.htm#m108


Comments