使用Tkinter的Treeview控件需要以下步骤:
from tkinter import *
from tkinter import ttk
root = Tk()
tree = ttk.Treeview(root)
tree["columns"] = ("column1", "column2")
tree.column("column1", width=100)
tree.column("column2", width=100)
tree.heading("column1", text="Column 1")
tree.heading("column2", text="Column 2")
# 添加根节点
tree.insert("", "end", text="Root", values=("value1", "value2"))
# 添加子节点
tree.insert("Root", "end", text="Child", values=("child value1", "child value2"))
scrollbar = ttk.Scrollbar(root, orient=VERTICAL, command=tree.yview)
tree.configure(yscrollcommand=scrollbar.set)
scrollbar.pack(side=RIGHT, fill=Y)
tree.pack()
root.mainloop()
完整的示例代码如下:
from tkinter import *
from tkinter import ttk
root = Tk()
tree = ttk.Treeview(root)
tree["columns"] = ("column1", "column2")
tree.column("column1", width=100)
tree.column("column2", width=100)
tree.heading("column1", text="Column 1")
tree.heading("column2", text="Column 2")
tree.insert("", "end", text="Root", values=("value1", "value2"))
tree.insert("Root", "end", text="Child", values=("child value1", "child value2"))
scrollbar = ttk.Scrollbar(root, orient=VERTICAL, command=tree.yview)
tree.configure(yscrollcommand=scrollbar.set)
scrollbar.pack(side=RIGHT, fill=Y)
tree.pack()
root.mainloop()
这样就可以创建一个简单的带有滚动条的Treeview控件了。
辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
推荐阅读: 如何设置treeview的字体颜色