本文实例讲述了python gui编程。分享给大家供大家参考,具体如下:
import os
from time import sleep
from tkinter import *
from tkinter.messagebox import showinfo
class dirlist(object):
def __init__(self, initdir=none):
self.top = tk()
self.label = label(master=self.top, text='directory lister v1.0')
self.label.pack()
self.cwd = stringvar(master=self.top)
self.dirl = label(self.top, fg='blue', font=('helvetica', 14, 'bold'))
self.dirl.pack()
self.dirfm = frame(master=self.top)
self.dirsb = scrollbar(master=self.dirfm)
self.dirsb.pack(side=right,fill=y) # fill=y,垂直填充空间排列
self.dirs = listbox(master=self.dirfm, height=15, width=50, yscrollcommand=self.dirsb.set)
self.dirs.bind('', func=self.setdirandgo) # ,双击显示路径列表
self.dirsb.config(command=self.dirs.yview)
self.dirs.pack(side=left, fill=both)
self.dirfm.pack()
self.dirn = entry(master=self.top, width=50, textvariable=self.cwd)
self.dirn.bind('', func=self.dols)
self.dirn.pack()
self.bfm = frame(master=self.top)
self.cleer = button(master=self.bfm, text='清除', command=self.clrdir, activeforeground='white',
activebackground='blue')
self.ls = button(master=self.bfm, text='显示列表', command=self.dols, activeforeground='white',
activebackground='green')
self.quit = button(master=self.bfm, text='退出', command=self.top.quit, activeforeground='white',
activebackground='red')
self.cleer.pack(side=left)
self.ls.pack(side=left)
self.quit.pack(side=left)
self.bfm.pack()
if initdir:
self.cwd.set(os.curdir)
self.dols()
def setdirandgo(self, ev=none):
self.last = self.cwd.get()
self.dirs.config(selectbackground='red')
chek = self.dirs.get(self.dirs.curselection())
if not chek:
chek = os.curdir
self.cwd.set(chek)
self.dols()
def dols(self, ev=none):
error = ''
tdir = self.cwd.get()
if not tdir:
tdir = os.curdir
if not os.path.exists(tdir):
error = tdir + ':未找到文件,请检查路径!'
elif not os.path.isdir(tdir):
error = tdir + ':不是一个路径!'
if error:
# self.cwd.set(error)
showinfo(title='提示',message=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.config(selectbackground='lightskyblue')
self.top.update()
return
if not os.path.isdir(tdir):
self.cwd.set('')
else:
self.cwd.set('获取目录内容中...')
self.top.update()
dirlist = os.listdir(tdir)
dirlist.sort()
os.chdir(tdir)
self.dirl.config(text=os.getcwd())
self.dirs.delete(0, end)
self.dirs.insert(end, os.curdir)
self.dirs.insert(end, os.pardir)
for eachfile in dirlist:
self.dirs.insert(end, eachfile)
self.cwd.set(os.curdir)
self.dirs.config(selectbackground='lightskyblue')
def clrdir(self, ev=none):
self.cwd.set('')
if __name__ == '__main__':
dir = dirlist(os.curdir)
mainloop()
效果如下:
希望本文所述对大家python程序设计有所帮助。
希望与广大网友互动??
点此进行留言吧!