zoukankan      html  css  js  c++  java
  • python之tkinter使用-文件系统遍历

      1 # tkinter:文件系统遍历
      2 import tkinter as tk, os
      3 from time import sleep
      4 
      5 
      6 class DirList(object):
      7     def __init__(self, initdir=os.curdir):
      8         self.top = tk.Tk()
      9         self.top.title('查找')
     10 
     11         self.top.geometry('400x500')  # 设置窗口大小
     12         self.label = tk.Label(self.top, text='文件列表', font=('宋体 -16 bold'))
     13         self.label.pack()
     14 
     15         # StringVar:字符串变量,特点是跟踪变量变化,及时显示在界面上
     16         self.cwd = tk.StringVar(self.top)
     17         self.cwd.set(initdir)
     18 
     19         # 当前目录显示标签
     20         self.dirl = tk.Label(self.top, fg='blue', font=('Helvetica -14 bold'))
     21         self.dirl.pack()
     22 
     23         # 新建框体容器,存放文件列表和滚动条
     24         self.dirfm = tk.Frame(self.top)
     25         # 滚动条
     26         self.dirsb = tk.Scrollbar(self.dirfm)
     27         self.dirsb.pack(side=tk.RIGHT, fill=tk.Y)
     28         # 列表框
     29         self.dirs = tk.Listbox(self.dirfm, height=23, width=60,
     30                                font=('Helvetica -14'),
     31                                yscrollcommand=self.dirsb.set)
     32         # 绑定setDirAndGo函数
     33         self.dirs.bind('<Double-1>', self.setDirAndGo)
     34         # 滑动框与列表关联
     35         self.dirsb.config(command=self.dirs.yview)
     36         self.dirs.pack(side=tk.LEFT, fill=tk.X)
     37         self.dirfm.pack(fill=tk.BOTH)
     38 
     39         # 输入框
     40         self.dirn = tk.Entry(self.top, width=60, font=('Helvetica -14'),
     41                              textvariable=self.cwd)
     42         # 监听回车事件,绑定doLS函数,函数必须要有event参数
     43         self.dirn.bind('<Return>', self.doLS)
     44         self.dirn.pack(fill=tk.BOTH)
     45 
     46         # 功能按钮框架包括三个按钮:清除、查询和退出。
     47         self.bfm = tk.Frame(self.top)
     48         self.clr = tk.Button(self.bfm, text='清除', width=6, command=self.clrDir,
     49                              activeforeground='white', activebackground='blue')
     50         self.ls = tk.Button(self.bfm, text='查询', width=6, command=self.doLS,
     51                             activeforeground='white', activebackground='green')
     52         self.quit = tk.Button(self.bfm, text='退出', width=6, command=self.top.quit,
     53                               activeforeground='white', activebackground='red')
     54         self.clr.pack(side=tk.LEFT, fill=tk.BOTH)
     55         self.ls.pack(side=tk.LEFT, fill=tk.BOTH)
     56         self.quit.pack(side=tk.LEFT, fill=tk.BOTH)
     57         self.bfm.pack()
     58 
     59     def clrDir(self, ev=None):
     60         '''清空文件路径输入框'''
     61         self.cwd.set('')
     62 
     63     def setDirAndGo(self, ev=None):
     64         '''设置文件路径并查询'''
     65         self.last = self.cwd.get()
     66         # 选中项背景默认为红色,后续修改为蓝色
     67         self.dirs.config(selectbackground='red')
     68         # 获取文件列表中选择项,没有选则输入框设置为当前目录路径
     69         try:
     70             # 获取目录列表中选中的文件名
     71             check = self.dirs.get(self.dirs.curselection())
     72         except:
     73             print("没有文件或文件错误!")
     74             return
     75 
     76         if not check:
     77             check = os.curdir
     78         self.cwd.set(check)
     79         self.doLS()
     80 
     81     def doLS(self, event=''):
     82         '''
     83         查询文件路径
     84         :param event:输入框回车事件触发参数
     85         :return:无
     86         '''
     87         error = ''
     88         tdir = self.cwd.get()
     89         if not tdir:
     90             tdir = os.curdir
     91 
     92         # 判断输入框中文件是否存在
     93         if not os.path.exists(tdir):
     94             error = tdir + ': no such file!'
     95         # 若文件存在,再判断是否是目录
     96         elif not os.path.isdir(tdir):
     97             error = tdir + ' is not directory!'
     98 
     99         if error:
    100             '''出现错误则提示在输入框内,2秒后还原'''
    101             self.dirn.config(fg='red')  # 输入框提示文字变为红色
    102             self.cwd.set(error)
    103             self.top.update()
    104             sleep(2)
    105             if not (hasattr(self, 'last') and self.last):
    106                 '''使用hasattr函数判断对象是否含有last属性或方法'''
    107                 self.last = os.curdir
    108             self.cwd.set(self.last)
    109             self.dirs.config(selectbackground='LightSkyBlue')
    110             self.dirn.config(fg='black')  # 输入框文字颜色还原
    111             self.top.update()
    112             return
    113 
    114         self.cwd.set('FETCHING DIRECTORY CONTENTS...')
    115         self.top.update()
    116 
    117         '''目录列表框操作'''
    118         self.dirs.delete(0, tk.END)  # 清空目录列表
    119         # self.dirs.insert(tk.END, os.curdir) # 添加当前目录"."
    120         self.dirs.insert(tk.END, os.pardir)  # 添加上级目录".."
    121 
    122         '''获取指定目录下的文件,在列表控件展示'''
    123         dirlist = os.listdir(tdir)
    124         dirlist.sort()
    125         os.chdir(tdir)  # 改变目录到指定路径
    126         for eachFlie in dirlist:
    127             self.dirs.insert(tk.END, eachFlie)
    128         self.cwd.set(os.getcwd())  # 在输入框中显示当前绝对路径
    129         self.dirl.config(text=os.getcwd())  # 上方标签显示当前路径
    130         self.dirs.config(selectbackground='LightSkyBlue')  # 选中时背景色为蓝色
    131         self.last = self.cwd.get()  # 记录最后一次路径
    132 
    133 
    134 def main():
    135     DirList('D:\')
    136     tk.mainloop()
    137 
    138 
    139 if __name__ == '__main__':
    140     main()

    截图:

  • 相关阅读:
    【leetcode】106. Construct Binary Tree from Inorder and Postorder Traversal
    【leetcode】105. Construct Binary Tree from Preorder and Inorder Traversal
    【leetcode】236. Lowest Common Ancestor of a Binary Tree
    【leetcode】235. Lowest Common Ancestor of a Binary Search Tree
    【leetcode】352. Data Stream as Disjoint Intervals
    【leetcode】897. Increasing Order Search Tree
    【leetcode】900. RLE Iterator
    BEC listen and translation exercise 26
    BEC listen and translation exercise 25
    BEC listen and translation exercise 24
  • 原文地址:https://www.cnblogs.com/gongxr/p/7765861.html
Copyright © 2011-2022 走看看