ttk.Treeview 根据单元格值设置单元格背景颜色

ttk.Treeview set cell background color based on cell value

我想自定义 ttk.Treeview 以便根据单元格中的值设置单元格背景颜色。这是我的 MWE,树视图为 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()

最后它应该是这样的(没有文字后面的白色背景):

提前致谢!

我不能完全按照你的意愿做,因为你可以像这样配置一行:

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()

据我所知,唯一的方法是创建一个 canvas 并对其进行一些处理。