温馨提示:本文翻译自stackoverflow.com,查看原文请点击:python - ttk.Treeview set cell background color based on cell value
python tkinter ttk

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

发布于 2021-05-01 18:31:26

我想自定义ttk.Treeview,以便根据单元格中的值设置单元格背景色。这是我的MWE,其中有一个Treeview作为表格:

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

最后,它应该看起来像这样(文本后面没有白色背景): 在此处输入图片说明

提前致谢!

查看更多

提问者
konze
被浏览
0
Atlas435 2020-06-30 22:00

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

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

据我所知,做到这一点的唯一方法是创建一个画布并在其上做一些工作。