Changing background color for every other line of text in a tkinter text box widget Changing background color for every other line of text in a tkinter text box widget tkinter tkinter

Changing background color for every other line of text in a tkinter text box widget


Tags allow you to change the background and foreground colors of a range of text (along with a few other attributes).

If you're adding data one line at a time you can apply a tag with each insert, and just alternate the tags for each line. For example, use the tag "odd" for the first insert, "even" for the second, "odd" for the third, and so on.

If you are inserting data in blocks, you can compute the starting and ending line numbers, and then iterate over every line to apply the tags.

Here's an example of the first technique:

import Tkinter as tkclass Example(tk.Frame):    def __init__(self, parent):        tk.Frame.__init__(self, parent)        self.text = tk.Text(self, wrap=None)        self.vsb = tk.Scrollbar(self, command=self.text.yview, orient="vertical")        self.text.configure(yscrollcommand=self.vsb.set)        self.vsb.pack(side="right", fill="y")        self.text.pack(side="left", fill="both", expand=True)        self.text.tag_configure("even", background="#e0e0e0")        self.text.tag_configure("odd", background="#ffffff")        with open(__file__, "r") as f:            tag = "odd"            for line in f.readlines():                self.text.insert("end", line, tag)                tag = "even" if tag == "odd" else "odd"if __name__ == "__main__":    root = tk.Tk()    Example(root).pack(fill="both", expand=True)    root.mainloop()

Here's a method that adds the highlighting after the fact:

def highlight(self):    lastline = self.text.index("end-1c").split(".")[0]    tag = "odd"    for i in range(1, int(lastline)):        self.text.tag_add(tag, "%s.0" % i, "%s.0" % (i+1))        tag = "even" if tag == "odd" else "odd"