Python tkinter 树形列表控件(Treeview)的使用简单举例

 

import tkinter as tk
from tkinter.ttk import Treeview

# 创建tkinter应用程序窗口
root = tk.Tk()
# 设置窗口大小和位置
root.geometry('500x300+400+300')
# 不允许改变窗口大小
root.resizable(False, False)
# 设置窗口标题
root.title('通信录管理系统')
# 使用Treeview组件实现表格功能
frame = tk.Frame(root)
frame.place(x=0, y=10, width=480, height=280)
# 滚动条
scrollBar = tk.Scrollbar(frame)
scrollBar.pack(side=tk.RIGHT, fill=tk.Y)
# Treeview组件,6列,显示表头,带垂直滚动条
tree = Treeview(frame,
                columns=('c1', 'c2', 'c3',
                         'c4', 'c5', 'c6'),
                show="headings",
                yscrollcommand=scrollBar.set)
# 设置每列宽度和对齐方式
tree.column('c1', width=70, anchor='center')
tree.column('c2', width=40, anchor='center')
tree.column('c3', width=40, anchor='center')
tree.column('c4', width=120, anchor='center')
tree.column('c5', width=100, anchor='center')
tree.column('c6', width=90, anchor='center')
# 设置每列表头标题文本
tree.heading('c1', text='姓名')
tree.heading('c2', text='性别')
tree.heading('c3', text='年龄')
tree.heading('c4', text='部门')
tree.heading('c5', text='电话')
tree.heading('c6', text='QQ')
tree.pack(side=tk.LEFT, fill=tk.Y)
# Treeview组件与垂直滚动条结合
scrollBar.config(command=tree.yview)


# 定义并绑定Treeview组件的鼠标单击事件
def tree_view_click(event):
    print(tree.selection())
    print(tree.item(tree.selection(), option="values"))
    pass


tree.bind('<ButtonRelease-1>', tree_view_click)  # 鼠标左键松开事件

# 插入演示数据
for i in range(10):
    tree.insert('', i, values=[str(i)] * 6)
# 运行程序,启动事件循环
root.mainloop()

 

 

import tkinter
from tkinter import ttk  # 导入内部包


def tree_view_click(*args):
    """根据选中行,弹出对话框,修改对应通信终端的配置"""
    print(tree.selection())  # 选定的iid组成的元组
    if len(tree.selection()) == 0:  # 元组的长度
        return
    str_tree_item = tree.selection()[0]    # iid
    values = tree.item(str_tree_item, option='values')  # 取值
    print(values)

    tree.item(tree.selection()[0], values=["a", "b"])  # 修改
    # 删除 全部 treeview 信息行
    for item in tree.get_children():  # used self.tree instead
        print(item)
        # tree.delete(item)

win = tkinter.Tk()
tree = ttk.Treeview(win, columns=('c1', 'c2'), selectmode="browse", show="tree headings")
tree.column('c1', anchor='center')
tree.column('c2', anchor='center')
# 参数:parent, index, iid=None, **kw (父节点,插入的位置,id,显示出的文本)
myidx = tree.insert("", 0, "中国", text="中国China", values=("1",1))  # ""表示父节点是根
myidx1 = tree.insert(myidx, 0, "广东", text="中国广东", values=("2",1))  # text表示显示出的文本,values是隐藏的值
myidx2 = tree.insert(myidx, 1, "江苏", text="中国江苏", values=("3",1))
myidy = tree.insert("", 1, "美国", text="美国USA", values=("4",2))
myidy1 = tree.insert(myidy, 0, "加州", text="美国加州", values=("5",2))
# tree.delete("加州")
tree.bind('<ButtonRelease-1>', tree_view_click)  # 鼠标左键松开事件

tree.pack()
win.mainloop()

 

posted @ 2023-06-06 12:51  辛河  阅读(3840)  评论(0编辑  收藏  举报