我可以更改 Python Treeview 中单个列的前景色吗?
Can I change the foreground color of a single column in Python Treeview?
这是我在 python tkinter 中的树视图的屏幕截图。
我想将 "Critical Level" 的前景(包括其子项)更改为 "Red" 或至少为红色。
style = Style()
style.configure("mystyle.Treeview", highlightthickness=0, bd=0, font=('open sans', 10), rowheight=20,
foreground='#e8e8e8')
style.configure("mystyle.Treeview.Heading", font=('open sans', 10, 'bold'), foreground='#000000')
您可以通过标记您的树视图项来实现,并使用 tag_configure
更改显示的颜色。
from tkinter import ttk
import tkinter as tk
root = tk.Tk()
tree = ttk.Treeview(root)
tree.pack()
c = tree.insert('', 'end', text='This is critical message', tags=('critical',))
tree.insert(c, 'end', text='This is child of critical message', tags=('critical',))
for i in range(5):
tree.insert('', 'end', text='This is non-critical message')
tree.tag_configure('critical', background='red',foreground="white")
root.mainloop()
注意:
Henry Yik 的回答在 python 3.7.3 和 3.8.0 中不起作用。但是,它适用于 python 3.6.2.
您可以使用答案中的代码找到行为差异:
这是我在 python tkinter 中的树视图的屏幕截图。 我想将 "Critical Level" 的前景(包括其子项)更改为 "Red" 或至少为红色。
style = Style()
style.configure("mystyle.Treeview", highlightthickness=0, bd=0, font=('open sans', 10), rowheight=20,
foreground='#e8e8e8')
style.configure("mystyle.Treeview.Heading", font=('open sans', 10, 'bold'), foreground='#000000')
您可以通过标记您的树视图项来实现,并使用 tag_configure
更改显示的颜色。
from tkinter import ttk
import tkinter as tk
root = tk.Tk()
tree = ttk.Treeview(root)
tree.pack()
c = tree.insert('', 'end', text='This is critical message', tags=('critical',))
tree.insert(c, 'end', text='This is child of critical message', tags=('critical',))
for i in range(5):
tree.insert('', 'end', text='This is non-critical message')
tree.tag_configure('critical', background='red',foreground="white")
root.mainloop()
注意: Henry Yik 的回答在 python 3.7.3 和 3.8.0 中不起作用。但是,它适用于 python 3.6.2.
您可以使用答案中的代码找到行为差异: