konze
konze

Reputation: 893

ttk.Treeview set cell background color based on cell value

I would like to customize a ttk.Treeview such that the cell background color is set according to the value in of a cell. Here is my MWE with a Treeview as a table:

try:
    import Tkinter as Tk
    from Tkinter import ttk
except ModuleNotFoundError:
    import tkinter as Tk
    from tkinter import ttk

if __name__ == '__main__':
    root = Tk.Tk()
    frame = Tk.Frame(root)

    tree = ttk.Treeview(frame.master, columns=("Name", "Hex Code"), show="headings")
    tree.heading('Name', text="Name")
    tree.heading('Hex Code', text="Hex Code")

    tree.pack()

    tree.insert('', 'end', values=("red","#ff0000"))
    tree.insert('', 'end', values=("green","#00ff00"))
    tree.insert('', 'end', values=("pink","#ff1493"))
    tree.insert('', 'end', values=("teal","#00cece"))

    root.mainloop()

In the end it should look like this (without the white background behind the text): enter image description here

Thanks in advance!

Upvotes: 0

Views: 5016

Answers (1)

Thingamabobs
Thingamabobs

Reputation: 8037

I can not exactly do what you wish, because you just can configure a row like:

try:
    import Tkinter as Tk
    from Tkinter import ttk
except ModuleNotFoundError:
    import tkinter as Tk
    from tkinter import ttk

if __name__ == '__main__':
    root = Tk.Tk()
    frame = Tk.Frame(root)

    tree = ttk.Treeview(frame.master, columns=("Name", "Hex Code"), show="headings")
    tree.heading('Name', text="Name")
    tree.heading('Hex Code', text="Hex Code")

    tree.pack()
    dct = {"red":"#ff0000",
           "green":"#00ff00",
           "pink":"#ff1493",
           "teal":"#00cece"}

    for key, value in dct.items():
        tree.insert("", "end",tag=key, values=(key,value))
        tree.tag_configure(tagname=key, background=value)
        

    root.mainloop()

The only way to do this, as far as I know, would be to create a canvas and do some work on it.

Upvotes: 2

Related Questions