Trying to colorize different rows in a Tkinter Treeview. I have gone through multiple docs and tutorials and believe I am doing it correctly (even tried variations like tags=("1",)) but nothing seems to work. Any help is appreciated.
import tkinter
from tkinter import ttk
mainWindow = tkinter.Tk()
tree = ttk.Treeview(mainWindow, height=8, column=['', '', '', '', ''])
tree.grid(row=2, column=0, columnspan=2)
tree.heading('#0', text='Numer')
tree.column('#0', width=150)
tree.heading('#1', text='Two')
tree.column('#1', width=200)
tree.heading('#2', text='Three')
tree.column('#2', width=200)
tree.heading('#3', text='Four')
tree.column('#3', width=80)
tree.heading('#4', text='Five')
tree.column('#4', width=40, stretch=False)
tree.tag_configure("1", background='green')
tree.tag_configure("2", background='#FF6666')
tree.tag_configure("3", background='#FFFF99')
tree.insert('', 'end', text="One", values=("2", "3", "4", "5"), tags="1")
tree.insert('', 'end', text="Two", values=("2", "3", "4", "5"), tags="2")
tree.insert('', 'end', text="Three", values=("2", "3", "4", "5"), tags="3")
tree.insert('', 'end', text="Four", values=("2", "3", "4", "5"), tags="1")
tree.insert('', 'end', text="Five", values=("2", "3", "4", "5"), tags="1")
mainWindow.mainloop()
Treeview styling was broken in Tkinter 8.6.9. Issue is marked as resolved, but for Tkinter 8.6.9 you can use a following workaround, by including it before your Treeview initialization:
def fixed_map(option):
# Fix for setting text colour for Tkinter 8.6.9
# From: https://core.tcl.tk/tk/info/509cafafae
#
# 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 = ttk.Style()
style.map('Treeview', foreground=fixed_map('foreground'),
background=fixed_map('background'))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With