#1:创建一个infoWindows类
import tkinter
from tkinter import ttk
import os
class InfoWindows(tkinter.Frame):
def __init__(self, master):
frame=tkinter.Frame(master)
#表格布局
frame.grid(row=0,column=2)
#创建进入按钮
#绑定变量
self.ev=tkinter.Variable()
self.entry=tkinter.Entry(frame,width=80,textvariable=self.ev)
self.entry.pack()
self.text=tkinter.Text(frame)
self.text.pack()
#2:创建一个treeFile的主类
import os
import tkinter
from treeWindows import TreeWindows
from infoWindows import InfoWindows
win=tkinter.Tk()
win.geometry('600x400+200+50')
win.title('目录')
path=r'D:\Python\Python源代码'
infoWin=InfoWindows(win)
treeWin=TreeWindows(win,path,infoWin)
win.mainloop()
#3:创建一个treeWindows类(最难)
import tkinter
from tkinter import ttk
import os
class TreeWindows(tkinter.Frame):
def __init__(self, master,path,otherWin): #master为主窗口,path为一级目录路径
frame=tkinter.Frame(master)
frame.grid(row=0,column=1)
self.otherWin=otherWin
self.path=path
self.tree=ttk.Treeview(frame)
self.tree.pack(side=tkinter.LEFT,fill=tkinter.Y)
#创建根树枝 ‘end’表示在后面添加,open表示是否显示
root=self.tree.insert('','end',text=self.getLastPath(path),open=True)
self.loadTree(root,path)
#滚动条
self.sy=tkinter.Scrollbar(frame)
self.sy.pack(side=tkinter.RIGHT,fill=tkinter.Y)
#关联
self.sy.config(command=self.tree.yview)
self.tree.config(yscrollcommand=self.sy.set)
#绑定事件
self.tree.bind('<<TreeviewSelect>>',self.func)
def func(self,event):
#找到触发事件的小部件
self.v=event.widget.selection()
for sv in self.v:
file=self.tree.item(sv)['text']
self.otherWin.ev.set(file)
apath=self.tree.item(sv)['values'][0] #绝对路径返回的是一个tuple,第一个数据是绝对路径
print(apath)
def getLastPath(self,path):
pathList=os.path.split(path)#将路径拆分成元组
return pathList[-1]
def loadTree(self,root,path):
for fileName in os.listdir(path):
#获取文件的绝对路径
absPath=os.path.join(path,fileName)
#插入树枝
treey=self.tree.insert(root,'end',text=self.getLastPath(absPath),values=(absPath))
#判断是否是目录
if os.path.isdir(absPath):
self.loadTree(treey,absPath)
#4:代码实现效果