Tkinter Treeview Create row content in different colors
The Treeview control has the tag_configure( ) method, which can be used to create a tag and then define the format of the tag, see the following command.
tag_configure("tagName", options, ...)
The first parameter tagName above is the tag name, which can be used to import this tag into the column data. options’ possible parameters are as follows.
(1) background
: the background color of the tag.
(2) font
: glyph setting.
(3) foreground
: label foreground color.
(4) image
: the image is displayed at the same time as the list.
To import the tags into the column using the insert( ) method, you need to add the tags parameter setting in this method, as follows.
insert(... , tags = "tagName")
The last point to explain is that the amount of data in real-world enterprise applications is usually very large, and it is not possible to use a single piece of data to build the Treeview control’s content step by step. In the following example, you use a dictionary to store data and then import the dictionary into the Treeview control in a round-robin fashion.
Example#1
In this example the even rows are shown in blue.
from tkinter import *
from tkinter.ttk import *
root = Tk()
root.title("apidemos.com")
stateCity = {"Eleanor":"Chicago",
"California":"LosAngeles",
"Texas":"Houston",
"Washington":"Seattle",
"aaa":"aaa1",
"bbb":"bbb1",
"ccc":"ccc1",
"ddd":"ddd1"}
# Create Treeview
tree = Treeview(root,columns=("cities"))
# Create column headings
tree.heading("#0",text="State") # Icon bar
tree.heading("cities",text="City")
# Formatting fields
tree.column("cities",anchor=CENTER)
# Create the content, line number from 1 to even lines is in light blue background
tree.tag_configure("evenColor",background="lightblue") # Set Tags
rowCount = 1
for state in stateCity.keys():
if (rowCount % 2 == 1):
tree.insert("",index=END,text=state,values=stateCity[state])
else:
tree.insert("",index=END,text=state,values=stateCity[state],
tags=("evenColor")) # Create light blue background
rowCount += 1 # Line number add 1
tree.pack()
root.mainloop()
Output: