Tuesday, August 2

Python For The People - A Wee Secret

Here is a neat way to apply color to text boxes, using the tag_config property and eliminating the need to manually set the background color per text box. First, define your desired color configurations and give them aliases:

txtBox = Text(self, width=80, height=20)
# configuration for red (alias = "r")
txtBox.tag_config("r", foreground="red")
# configuration for blue (alias = "b")
txtBox.tag_config("b", foreground="blue")

This creates a list of alias/configuration pairs associated to the textbox's config object. Next, apply the configuration aliases' to the target text boxes, together with the content to be displayed:

txtBox.insert(END,"I am red ", "r")
txtBox.insert(END,"or I am blue\n", "b")

Smooth.

No comments: