1 参考资料
python ttk Treeview的插入、清空、各种点击事件、获取条目值、标题单击排序
2 基本用法
tv = ttk.Treeview(root, height=20, selectmode = 'browse',show= 'tree')
option | description |
---|---|
columns | 列标识符的列表,用于指定列数及其名称。 |
displaycolumns | 列标识符(符号或整数索引)的列表,用于指定显示哪些数据列及其出现的顺序,或字符串“ #all”。 |
height | 指定应可见的行数。注意:请求的宽度由列宽度的总和确定。 |
padding | 指定窗口小部件的内部填充。填充是最多四个长度规范的列表。 |
selectmode | 控制内置类绑定如何管理选择。 “extended”, “browse” 或 “none”。如果设置为 “extended”( 默认),则可以选择多个项目。如果为“browse” ,则一次将仅选择一个项目。如果为“ none”,则选择不会更改。 |
show | 包含零个或多个以下值的列表,指定要显示树的哪些元素。
默认值为“tree headings”,即显示所有元素。 注意:即使未指定show =“ tree”,列#0始终引用树列。 |
3 点击事件
事件 | 代码 |
鼠标左键单击按下 | 1/Button-1/ButtonPress-1 |
鼠标左键单击松开 | ButtonRelease-1 |
鼠标右键单击 | 3 |
鼠标左键双击 | Double-1/Double-Button-1 |
鼠标右键双击 | Double-3 |
鼠标滚轮单击 | 2 |
鼠标滚轮双击 | Double-2 |
鼠标移动 | B1-Motion |
鼠标移动到区域 | Enter |
鼠标离开区域 | Leave |
获得键盘焦点 | FocusIn |
失去键盘焦点 | FocusOut |
键盘事件 | Key |
回车键 | Return |
控件尺寸变话 | Configure |
4 案例:点击目录所在行,展示对应功能的结果
from tkinter import *
from tkinter import ttk
def ds(root):
s=Label(root,text='目录1-test')
s.pack()
def ctm(root):
c=Label(root,text='目录2-test')
c.pack()
def lts(root):
l=Label(root,text='目录3-test')
l.pack()
root = Tk()
root.geometry('800x600+250+50')
root.resizable(False,False)
root.title('主界面')
tv = ttk.Treeview(root, height=20, selectmode = 'browse',show= 'tree')
tv.insert('',0,text='----------------------')
tv.insert('',1,text='目录1')
tv.insert('',2,text='目录2')
tv.insert('',3,text='目录3')
tv.place(x=30,y=20)
def all(event):
item = tv.selection() #'I001'、'I002'
if item:
txt = tv.item(item[0],'text')
print(item,' ',txt)
if txt == '目录1':
ds(root)
elif txt == '目录2':
ctm(root)
elif txt == '目录3':
lts(root)
tv.bind('<ButtonRelease-1>',all)
root.mainloop()
运行结果: