ttk Treeview: 交替行颜色
我想给treeview
这个小部件设置样式,让它的每一行背景颜色不一样。比如说,第一、三、五行的背景是白色,第二、四、六行的背景是淡蓝灰色。
我还想设置gridlines
,也就是网格线。
6 个回答
1
这个代码可以直接运行,不需要额外的模块……你可以修改一下代码,让它适应你自己的需求。
from Tkinter import *
import ttk
class Test(Frame):
def __init__(self):
Frame.__init__(self)
self.pack()
self.listbox()
self.buttons()
def listbox(self):
global new_customer_lb
scrollbar = Scrollbar(self, orient="vertical")
new_customer_lb = ttk.Treeview(self, columns=('ID','First Name','Last Name'))
new_customer_lb['show']='headings'
new_customer_lb.heading('#1', text= 'ID')
new_customer_lb.column('#1', width=50, stretch=NO)
new_customer_lb.heading('#2', text= 'First Name')
new_customer_lb.column('#2', width=100, stretch=NO)
new_customer_lb.heading('#3', text= 'Last Name')
new_customer_lb.column('#3', width=100, stretch=NO)
new_customer_lb.configure(yscroll = scrollbar.set, selectmode="browse")
scrollbar.config(command=new_customer_lb.yview)
new_customer_lb.pack()
def buttons(self):
load = Button(self, text='show customers', command=lambda:self.load_working_customers())
test = Button(self, text='test new colors', command=lambda:self.test_colors())
load.pack()
test.pack()
def load_working_customers(self):
new_customer_lb.delete(*new_customer_lb.get_children())
for a in range(0,10):
new_customer_lb.insert('','end', values=(a,'first','last'))
def test_colors(self):
new_customer_lb.delete(*new_customer_lb.get_children())
new_customer_lb.tag_configure("evenrow",background='white',foreground='black')
new_customer_lb.tag_configure("oddrow",background='black',foreground='white')
for a in range(0,10):
if a % 2 == 0:
new_customer_lb.insert('','end', values=(a,'first','last'), tags=('evenrow',))
if a % 2 != 0:
new_customer_lb.insert('','end', values=(a,'first','last'), tags=('oddrow',))
root = Tk()
app = Test()
app.mainloop()
3
我知道这个问题有点老了,但我想说的是,在创建树结构后立刻配置标签也是可以的(也就是说,当树里还没有任何项目时)。之后再添加项目时,它们会根据自己的“奇数行”或“偶数行”标签,自动被赋予相应的背景颜色。
52
几个月前我也遇到过这个问题。
根据tk文档的说法:
You can assign a list of tags to each item using the "tags"
item configuration option (again, when creating the item or later on).
Tag configuration options can then be specified, which will then
apply to all items having that tag.
简单来说,你可以给所有奇数行加一个标签,给每个偶数行加一个不同的标签,然后再设置这些标签的样式。
当你在树形视图中创建项目时,要给它们添加标签:
tree.insert('', 'end', text = 'your text', tags = ('oddrow',))
这段代码在tree
中创建了一个元素,并且tags
参数将标签'oddrow'分配给这个元素。
一旦你用'oddrow'和'evenrow'标签创建了所有元素,就可以为这些标签上色:
tree.tag_configure('oddrow', background='orange')
tree.tag_configure('evenrow', background='purple')