Python+Tkinter实现窗体目录结构和文件内容显示

需要用到的Python模块

  • tkinter模块
  • os模块
  • ttk模块(此处为方便编写单独引入ttk模块)

实现目标

在窗体中显示指定目录的结构,或文件内容

实现逻辑

创建窗体

import tkinter
from treeWindow import TreeWindow
from infoWindow import InfoWindow

win = tkinter.Tk()

win.title("目录结构树状显示")
win.geometry('900x400+200+50')

#路径使用正斜杠 / 替代反斜杠 \ 以使文件路径可以完整保存
path = r"D:/Python模块"

infoWin = InfoWindow(win)
treeWin = TreeWindow(win,path, infoWin)

win.mainloop()

创建树状数据显示窗口类

import tkinter
from tkinter import ttk
import os

class TreeWindow(tkinter.Frame):
    def __init__(self,master,path, otherWin):
        self.otherWin = otherWin

        frame = tkinter.Frame(master)
        frame.grid(row=0, column=0)

        # 创建Frame
        self.tree = ttk.Treeview(frame)
        self.tree.pack(side=tkinter.LEFT, fill=tkinter.Y)
        # 加载根目录
        curPath = self.getLastPaht(path)
        root = self.tree.insert("", 'end', text=curPath, open=True, values=(path))
        # 加载子目录
        self.loadTree(root,path)
        #添加滚动条
        self.sc = tkinter.Scrollbar(frame)
        self.sc.pack(side=tkinter.RIGHT, fill=tkinter.Y)
        self.sc.config(command=self.tree.yview)
        self.tree.config(yscrollcommand=self.sc.set)


        #绑定事件
        self.tree.bind("<>", self.func)

	
    def func(self,event):
        self.v = event.widget.selection()
        for sv in self.v:
            file = self.tree.item(sv)['text']
            self.otherWin.var.set(file)
            absPath = self.tree.item(sv)['values'][0]
            # print(absPath)
            if self.file_extension(absPath) == '.py':
                with open(absPath, 'r', encoding='utf-8') as f:
                    self.otherWin.txt.insert(tkinter.INSERT, f.read())
                    
	#获取文件后缀名
    def file_extension(self,filePath):
        return os.path.splitext(filePath)[1]


    def loadTree(self,parent,parentPath):
        for fileName in os.listdir(parentPath):
            pathList = [parentPath, fileName]
            absPath = '/'.join(pathList)
            # 插入一级树枝
            treep = self.tree.insert(parent, 'end', text=self.getLastPaht(absPath), values=(absPath))
            # 判断是否是目录
            if os.path.isdir(absPath):
                self.loadTree(treep,absPath)

	#获取最后层级的目录用于显示
    def getLastPaht(self,path):
        pathList = os.path.split(path)
        return pathList[-1]
        

创建文本显示控件的窗口类

import tkinter

class InfoWindow(tkinter.Frame):
    def __init__(self, master):
        frame = tkinter.Frame(master)
        frame.grid(row=0, column=1)

        self.var = tkinter.Variable()
        self.entry = tkinter.Entry(frame, textvariable=self.var)
        self.entry.pack()

        self.txt = tkinter.Text(frame)
        self.txt.pack()

至此,程序已可以浏览指定路径的所有子目录并显示后缀为.py的文件内容

你可能感兴趣的:(Python学习)