使用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控件了。