treeview控件使⽤详解python_PythonGUI编程⼊门(31)-
Treeview控件
Treeview是Tkinter8.5新引⼊的控件,可以⽤于实现较为复杂的GUI界⾯。本⽂使⽤⼀个FileBrowser实例来说明它的⽤法。
构建主窗⼝和退出菜单的代码和前⼀篇⽂章⼏乎相同:
root = Tk()root.title('Tkinter Treeview and PanedWindow Demo V1.0')id_rowconfigure(0,
weight=id_columnconfigure(0, weight=1)screen_w = root.winfo_screenwidth()screen_h =
root.winfo_screenheight()root.maxsize(width=screen_w, height=screen_h)rw = int(screen_w / 2)rh = int(screen_h /
ry('{}x{}+{:g}+{:g}'.format(rw, rh, rw / 2, rh / 2))top_menu = Menu(fig(menu=top_menu)file_menu = Menu(top_menu, tearoff=False)top_menu.add_cascade(label='File', menu=file_menu)file_menu.add_command(label="Exit", command=root.quit)
构建⼀个⽔平⽅向的PanedWindow控件,grid布局时sticky属性设置为四⾯填充。
paned_window = PanedWindow(root, orient=HORIZONTAL)id(row=0, column=0, sticky='eswn')
构建管理左侧控件的Frame对象:
tree_area = Frame(paned_window)id_rowconfigure(0, weight=1)id_columnconfigure(0,
weight=1)paned_window.add(tree_area)
准备Treeview图标⽂件:
cur_path = os.path.abspath(os.path.dirname(__file__))pc_image = PhotoImage(file=cur_path +
'\\images\\pc.png')drive_image = PhotoImage(file=cur_path + '\\images\\drive.png')folder_image =
PhotoImage(file=cur_path + '\\images\\folder.png')file_image = PhotoImage(file=cur_path + '\\images\\file.png')
构建Treeview控件。将show属性指定为'tree'可以消除顶部的标题⾏。
tree_view = Treeview(tree_area, show='tree', selectmode='browse')id(row=0, column=0, sticky='nsew')
添加⽔平和垂直滚动条:
scroll_ty = Scrollbar(tree_area, orient=VERTICAL, command=tree_view.yview)id(row=0, column=1,
sticky=N+S)tree_view['yscrollcommand']=scroll_ty.setscroll_tx = Scrollbar(tree_area, orient=HORIZONTAL,
command=tree_view.xview)id(row=1, column=0, sticky=E+W)tree_view['xscrollcommand']=scroll_tx.set
增加根节点及驱动器节点:
pc_node= tree_view.insert('', 'end',('COMPUTERNAME'),image=pc_image,open=False)for c in
string.ascii_uppercase:disk = c + ':'if os.path.isdir(disk):drive_node = tree_view.insert(pc_node, 'end', text=disk,
image=drive_image)
给定节点,获得节点路径的函数:
def node_path(node):path = ''parent = nodewhile parent:node_text = tree_view.item(parent, 'text')if len(path) > 0:path =
os.path.join(node_text, path)else:path = node_textparent = tree_view.parent(parent)return path
由于磁盘⽬录的结构⼀般都会⾮常复杂,因此本⽰例采⽤以下策略:
展开节点时才会读⼊下级节点⽬录结构
关闭节点时删除下级节点的⽬录结构
def open_node(event):focus = tree_view.focus()for node in
_children(focus):insert_child_items(node)tree_view.bind('<>', open_node)def close_nod
e(event):focus =
tree_view.focus()for node in _children(focus):children = _children(node)for c in
children:tree_view.delete(c)tree_view.bind('<>', close_node)
insert_child_items的实现如下:
def insert_child_items(parent_node):path = node_path(parent_node)if os.path.isdir(path):try:dir_items = os.scandir(path)for item in dir_items:if item.is_dir() and ('.$'.find(item.name[0])<0):tree_view.insert(parent_node, 'end', text=item.name,
image=folder_image)except Exception as e:print(e)
增加下级节点的⼦节点操作以⽬录为操作对象。这个操作还会排除系统⽂件和隐藏⽂件。异常处理的对象是没有访问权限等情况。
构建右侧显⽰区域:
python新手编程100例
detail_area = Frame(paned_window)id_rowconfigure(0, weight=1)id_columnconfigure(0,
weight=1)paned_window.add(detail_area)
构建列表形式的Treeview:
list_view = Treeview(detail_area)list_view['columns'] = ('#1', '#2', "#3", '#4')lumn("#0", width=150, minwidth=150, stretch=YES)lumn("#1", width=150, minwidth=150, stretch=YES)lumn("#2", width=100,
minwidth=100, stretch=YES)lumn("#3", width=100, minwidth=100, stretch=NO)lumn("#4",
width=100, minwidth=50, stretch=YES)list_view.heading("#0", text="Name", anchor=W)list_view.heading("#1", text="Date modified", anchor=W)list_view.heading("#2", text="Type", anchor=W)list_view.heading("#3", text="Size",
anchor=W)id(row=0, column=0, sticky='nsew')
构建Scrollbar和Sizegrip控件:
scroll_fy = Scrollbar(detail_area, orient=VERTICAL, command=list_view.yview)id(row=0, column=1,
sticky=N+S)list_view['yscrollcommand']=scroll_fy.setscroll_fx = Scrollbar(detail_area, orient=HORIZONTAL,
command=list_view.xview)id(row=1, column=0,
sticky=E+W)list_view['xscrollcommand']=scroll_fx.setSizegrip(detail_area).grid(row=1, column=1)
当左侧Treeview的被选节点发⽣变化时,获取对应⽬录中的⽂件并表⽰在右侧列表形式的Treeview中。
def select_node(event):children = _children('')for c in children:list_view.delete(c)focus = tree_view.focus()path = node_path(focus)if os.path.isdir(path):try:dir_items = os.scandir(path)iid = 0for item in dir_items:if item.is_file() and
('.$'.find(item.name[0]) < 0):stat_info = os.stat(item.path)m_time = time.strftime("%Y/%m/%d %H:%M",
time.localtime(stat_info.st_mtime))type = ' File'dot_pos = item.name.rfind('.')if dot_pos > 0:type =
item.name[dot_pos+1:].upper() + typelist_view.insert('', 'end', str(iid), text=item.name, values=(m_time, type,
stat_info.st_size))iid += 1except Exception as e:print(e)tree_view.bind('<>', select_node)
软件的演⽰视频如下:
完整代码可以从以下地址下载:
觉得本⽂有帮助?请分享给更多⼈。
关注【⾯向对象思考】,轻松学习每⼀天!
有任何疑问,欢迎留⾔提问或讨论。
⾯向对象设计,⾯向对象编程,⾯向对象思考!

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。