Dynamic text color

John Posner jjposner at optimum.net
Sat Jan 2 20:38:58 EST 2010


On Sat, Jan 2, 2010 at 1:47 PM, Dave McCormick wrote:

> WooHoo!!!
> I got it!!! Yup, I am sure it can be optimized but it works!!!

Hmmm ... it doesn't work for me ...

<snip>

  ####RED########
>    for word in redList:
>        new_Rword(complete, word)      def new_Rword(complete, word):
>    Tbox.tag_remove(word, "1.0", END)
>    for matchobj in re.finditer(word, complete):
>        start,end =  matchobj.span()               Tbox.tag_add("red", 
> "1.0 + %d chars" % start,"1.0 + %d chars" % end)
>    Tbox.tag_config("red", foreground="red")

How *could* this work, Dave, since you call function new_Rword() before 
you define it? I rearranged the statements in your program, and it now 
works for me:

#---------------------------------------------
from Tkinter import *
import re

redList = "red dog".split()
blueList = "blue ball".split()
greenList = "green grass".split()

def get_position(event):
     complete = Tbox.get("1.0", END)
     for word in redList:
         new_Rword(complete, word)
     for word in blueList:
         new_Bword(complete, word)
     for word in greenList:
         new_Gword(complete, word)

def new_Rword(complete, word):
     Tbox.tag_remove(word, "1.0", END)
     for matchobj in re.finditer(word, complete):
         start,end =  matchobj.span()
         Tbox.tag_add("red", "1.0 + %d chars" % start,"1.0 + %d chars" % 
end)

def new_Bword(complete, word):
     Tbox.tag_remove(word, "1.0", END)
     for matchobj in re.finditer(word, complete):
         start,end =  matchobj.span()
         Tbox.tag_add("blue", "1.0 + %d chars" % start,"1.0 + %d chars" 
% end)

def new_Gword(complete, word):
     Tbox.tag_remove(word, "1.0", END)
     for matchobj in re.finditer(word, complete):
         start,end =  matchobj.span()
         Tbox.tag_add("green", "1.0 + %d chars" % start,"1.0 + %d chars" 
% end)

root = Tk()
Tbox = Text(root, width=40, height=15, wrap=CHAR,
            font="Times 14 bold", bg="#dddddd")
Tbox.tag_config("red", foreground="red")
Tbox.tag_config("blue", foreground="blue")
Tbox.tag_config("green", foreground="green")

Tbox.pack()
Tbox.bind("<KeyRelease>", get_position)
Tbox.focus()
root.mainloop()
#---------------------------------------------

This version also has the advantage of defining each function just once, 
instead of multiple times on each keystroke! Still to-do:

* rename get_position() to get_complete_text()

* replace new_Rword(), new_Bword(), and new_Gword() with a single 
function that has an extra parameter, "color".

Keep at it!

-John




More information about the Python-list mailing list