尝试在Tkinter树视图中为不同的行着色。我已经阅读了多个文档和教程,并相信自己做得正确(甚至尝试过类似tag =(“ 1”,)之类的变体),但似乎没有任何效果。 任何帮助表示赞赏。
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()
答案 0 :(得分:1)
Treeview样式在Tkinter 8.6.9中被破坏。 Issue被标记为已解决,但是对于Tkinter 8.6.9,您可以使用以下变通办法,方法是在初始化Treeview之前将其包括在内:
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'))