self.tree = ttk.Treeview(self.rightTopFrame) #self.rightTopFrame是treeview的父容器canvas
style = ttk.Style()
MON_FONTSIZE = 14
style.configure('Treeview.Heading', font=(None, MON_FONTSIZE),
rowheight=int(MON_FONTSIZE * 5.2))
style.configure('Treeview', font=(None, MON_FONTSIZE),
rowheight=int(MON_FONTSIZE * 5.2))
self.tree["columns"] = ("姓名", '血量')
self.tree.heading("姓名", text="姓名") # 显示表头
self.tree.heading("血量", text="血量")
self.tree.column("姓名", width=100, anchor="center")
self.tree.column("血量", width=800, anchor="center")
self.tree.tag_configure("mine", foreground="red")
self.tree.tag_configure("others", foreground="blue")
self.tree.tag_configure("finish", foreground="green")
self.tree.place(relx=0.004, rely=0.028, relwidth=0.964, relheight=0.95)
"""
定义滚动条控件
orient为滚动条的方向,vertical--纵向,horizontal--横向
command=self.tree.yview 将滚动条绑定到treeview控件的Y轴
"""
self.VScroll1 = Scrollbar(self.rightTopFrame, orient='vertical', command=self.tree.yview)
self.VScroll1.place(relx=0.971, rely=0.028, relwidth=0.024, relheight=0.958)
# 给treeview添加配置
self.tree.configure(yscrollcommand=self.VScroll1.set)
写入数据:写入之前删除节点即可实现写入的数据永远是最新的。(错误思路:用JS的思维来做,数据改变即新数据产生的时候就去判断treeview是否有节点,有才执行删除,否则不删除)
# 删除原节点
for _ in map(self.tree.delete, self.tree.get_children("")):
pass
index = 0
for item in self.getAttackLog(): # 写入数据
if item.get("type") == 'enemy':
self.tree.insert('', index, values=(item.get("type"), item.get("msg")),
tags="others")
elif item.get("type") == 'finish':
self.tree.insert('', index, values=(item.get("type"), item.get("msg")),
tags="finish")
else:
self.tree.insert('', index, values=(item.get("type"), item.get("msg")),
tags="mine")
index += 1
self.tree.pack(side=tkinter.LEFT, padx=5, pady=20)