Reputation: 137
I am trying to change the background color of the rows in treeview using tags but unable to get the success. Following is my code:
def display_device_status(self, colnames):
# root = Tk()
# self.root.title('Device Status')
# self.root.resizable(width=FALSE, height=FALSE)
# tree = ttk.Treeview(self.root, height=25, column=("col1", "col2"), show="headings", selectmode="browse")
# tree.heading('#1', text='MAC')
# tree.column('#1',width=290)
# tree.heading('#2', text='Status')
# tree.column('#2',width=290)
tree = ttk.Treeview(self.root, height=25, column=colnames, show="headings", selectmode="browse")
# tree.option_add()
for eachcol in colnames:
tree.heading(column=eachcol, text=eachcol)
tree.column(column=eachcol, width=290, minwidth=0)
vsb = ttk.Scrollbar(self.root, orient="vertical")
vsb.configure(command=tree.yview)
tree.configure(yscrollcommand=vsb.set)
tree.pack(side="left")
vsb.pack(side="right", fill="y")
# viewing_records(tree)
records = tree.get_children()
for element in records:
tree.delete(element)
conn = sqlite3.connect('Gateway_Log.db')
cursor = conn.cursor()
query_result = cursor.execute("SELECT * FROM Status")
for row in query_result:
if row[1] == 1:
tree.insert("", 'end', values=(row[0], 'Online'), tags = ('123',))
else:
tree.insert("", 'end', values=(row[0], 'Offline'), tags=('456',))
tree.tag_configure('123', background='orange')
tree.tag_configure('456', background='purple')
cursor.close()
conn.close()
when I run this code every time I am able to see background color as while only.
Please help me to change the background color of row.
Upvotes: 0
Views: 1400
Reputation: 16169
You are changing the color of the rows the right way, but there is currently a bug with treeviews in Tcl: https://core.tcl-lang.org/tk/tktview?name=509cafafae so the row color set from the tag is overridden by the treeview background color set by the style.
While waiting for the fixed version of tcl/tk, you can use the fix suggested in the bug ticket:
style = ttk.Style()
def fixed_map(option):
# Returns the style map for 'option' with any styles starting with
# ("!disabled", "!selected", ...) filtered out
# style.map() returns an empty list for missing options, so this should
# be future-safe
return [elm for elm in style.map("Treeview", query_opt=option)
if elm[:2] != ("!disabled", "!selected")]
style.map("Treeview",
foreground=fixed_map("foreground"),
background=fixed_map("background"))
Upvotes: 1