我们设计一个这样的程序,给定目录,能够显示目录下的文件;
双击目录,能够显示这个目录下的文件;#!/usr/bin/env python # encoding: utf-8 import os from time import sleep from Tkinter import * class DirList(object): def __init__(self,initdir=None): """ """ self.top=Tk() self.title_label=Label(self.top,text="Directory Lister V1.1") self.title_label.pack() self.cwd=StringVar(self.top) self.cwd_lable=Label(self.top,fg='blue',font=('Helvetica',12,'bold')) self.cwd_lable.pack() self.dirs_frame=Frame(self.top) self.sbar=Scrollbar(self.dirs_frame) self.sbar.pack(side=RIGHT,fill=Y) self.dirs_listbox=Listbox(self.dirs_frame,height=15,width=50,yscrollcommand=self.sbar.set) self.dirs_listbox.bind('<Double-1>',self.setDirAndGo) self.dirs_listbox.pack(side=LEFT,fill=BOTH) self.dirs_frame.pack() self.dirn=Entry(self.top,width=50,textvariable=self.cwd) self.dirn.bind("<Return>",self.doLS) self.dirn.pack() self.bottom_frame=Frame(self.top) self.clr=Button(self.bottom_frame,text="Clear",command=self.clrDir,activeforeground='white',activebackground='blue') self.ls=Button(self.bottom_frame,text="LS",command=self.doLS,activeforeground='white',activebackground='blue') self.quit=Button(self.bottom_frame,text="Quit",command=self.top.quit,activeforeground='white',activebackground='blue') self.clr.pack(side=LEFT) self.ls.pack(side=LEFT) self.quit.pack(side=LEFT) self.bottom_frame.pack() if initdir: self.cwd.set(os.curdir) self.doLS() def clrDir(self,ev=None): #self.cwd.set('') self.dirs_listbox.delete(first=0,last=END) def setDirAndGo(self, ev=None): """pass :ev: @todo :returns: @todo """ self.last=self.cwd.get() self.dirs_listbox.config(selectbackground='red') check=self.dirs_listbox.get(self.dirs_listbox.curselection()) if not check: check=os.curdir #check is the selected item for file or directory self.cwd.set(check) self.doLS() def doLS(self,ev=None): error="" self.cwd_lable.config(text=self.cwd.get()) tdir=self.cwd.get()#get the current working directory if not tdir: tdir=os.curdir if not os.path.exists(tdir): error=tdir+':no such file' elif not os.path.isdir(tdir): error=tdir+":not a directory" if error:#if error occured self.cwd.get(error) self.top.update() sleep(2) if not (hasattr(self,'last') and self.last): self.last=os.curdir self.cwd.set(self,last) self.dirs_listbox.config(selectbackground='LightSkyBlue') self.top.update() return self.cwd.set("fetching dir contents") self.top.update() dirlist=os.listdir(tdir) dirlist.sort() os.chdir(tdir) self.dirs_listbox.delete(0,END) self.dirs_listbox.insert(END,os.curdir) self.dirs_listbox.insert(END,os.pardir) for eachfile in dirlist: self.dirs_listbox.insert(END,eachfile) self.cwd.set(os.curdir) self.dirs_listbox.config(selectbackground='LightSkyBlue') def main(): d=DirList(os.curdir) mainloop() if __name__ == '__main__': main()