用tkinter的treeview写一个树状列表的代码
时间: 2024-06-12 21:05:55 浏览: 134
以下是一个简单的树状列表的例子,使用了tkinter的treeview组件:
```python
import tkinter as tk
from tkinter import ttk
class TreeViewExample:
def __init__(self):
self.tree = None
self.setup_ui()
def setup_ui(self):
root = tk.Tk()
root.title("Tree View Example")
# Create a Treeview widget
self.tree = ttk.Treeview(root)
self.tree.pack(expand=True, fill=tk.BOTH)
# Define the columns
self.tree["columns"] = ("Name", "Age", "Gender")
# Add columns
self.tree.column("#0", width=0, stretch=tk.NO)
self.tree.column("Name", anchor=tk.W, width=100)
self.tree.column("Age", anchor=tk.CENTER, width=50)
self.tree.column("Gender", anchor=tk.W, width=50)
# Add headings
self.tree.heading("#0", text="", anchor=tk.W)
self.tree.heading("Name", text="Name", anchor=tk.W)
self.tree.heading("Age", text="Age", anchor=tk.CENTER)
self.tree.heading("Gender", text="Gender", anchor=tk.W)
# Add items to the treeview
parent = self.tree.insert("", tk.END, text="Parent", open=True)
self.tree.insert(parent, tk.END, text="Child 1", values=("John", "25", "Male"))
self.tree.insert(parent, tk.END, text="Child 2", values=("Mary", "20", "Female"))
# Bind double click event to handle item selection
self.tree.bind("<Double-1>", self.on_item_selected)
root.mainloop()
def on_item_selected(self, event):
item = self.tree.selection()[0]
print("Selected item:", item)
if __name__ == "__main__":
TreeViewExample()
```
该例子创建了一个包含三列(姓名,年龄和性别)的树状列表,并向其中添加了两个子项(Child 1和Child 2)作为父项(Parent)的子节点。还绑定了双击事件(on_item_selected)来处理项目的选择。
阅读全文