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):
Thanks in advance!
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.
Thanks you. I'm fine with coloring a whole row. However, your example uses tags and if I want to have the user select an arbitrary color at run time am I still able to set the color of a row?
You think of to colorize the row after clicking on the item?
I think of colorizing the row when an item is edited or added and the row color should be the color of hex code value.
Yes you can do edit them. In the line of tag_configure "key" and "value" are just equally to strings that are stored in the dict. You just need to copy the line and edit them with your new strings. You just should remove the old tag to avoid duplicated tags. tcl.tk/man/tcl8.6/TkCmd/ttk_treeview.htm#M59