Reputation: 5207
I have a text box widget that I use just to print debug data to and I want to change the background color for each line of text within the text box widget to make things easier to read. I have been looking at how to highlight text with the text box widget, but cannot seem to figure out how to get the background color for each line to change. Is it possible to do this?
So far I have tried using tags, but I think I'm misunderstanding how to use them or something because I'm having trouble getting any results. The searches I have done on google come up with questions regarding highlighting specific words, and I couldn't find any similar scenarios to work off of.
If anybody knows of some resources I can look at, or could point me in the right direction, that would be wonderful. An example would be even better, but I don't expect anybody to do the leg-work for me.
Thanks!
Upvotes: 4
Views: 3970
Reputation: 386372
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 tk
class 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"
Upvotes: 6