背景:同事需要,未进行代码类的编写 ,集成日志功能,获取电脑本地账户,GUI界面,压缩文件夹的功能
from tkinter import *
from tkinter.filedialog import askdirectory
import zipfile
import os
from datetime import datetime
import getpass
import logging
user = getpass.getuser()
tk=Tk()
tk.title("小工具")
var=IntVar()
path1 = StringVar()
default = StringVar()
default.set('请输入创建的文件夹名称')
username = StringVar()
username.set('请确认用户:'+user)
def OpenFile():
path_ = askdirectory()
path1.set(path_)
def client_exit():
exit()
def Setfile():
startdir = path1.get() #如此获取内容,更正
file_news = datetime.now().strftime("%Y-%m-%d_%H_%M_%S")+'.zip' # 压缩后文件夹的名字
z = zipfile.ZipFile(file_news,'w',zipfile.ZIP_DEFLATED) #参数一:文件夹名
for dirpath, dirnames, filenames in os.walk(startdir):
fpath = dirpath.replace(startdir,'') #这一句很重要,不replace的话,就从根目录开始复制
fpath = fpath and fpath + os.sep or ''#这句话理解我也点郁闷,实现当前文件夹以及包含的所有文件的压缩
for filename in filenames:
try:
z.write(os.path.join(dirpath, filename),fpath+filename)
print ('压缩成功')
except Exception as e:
print('e')
logging.basicConfig(level=logging.DEBUG,format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s', \
datefmt='%a, %d %b %Y %H:%M:%S',filename="test.log",filemode='a')
logging.debug("User %s is loging" % user)
z.close()
menubar = Menu(tk)
filemenu = Menu(menubar)
menubar.add_command(label='选择文件', command= OpenFile)
menubar.add_command(label='压缩文件', command= Setfile)
menubar.add_command(label='退出', command= client_exit)
tk['menu'] = menubar
#标签控件,显示文本和位图,展示在第一行
Label(tk,text="上传者").grid(row=0,sticky=E)#靠右
Label(tk,text="本地目录").grid(row=1,sticky=W)#第二行,靠左
Label(tk,text="目标目录").grid(row=2,sticky=W)
#输入控件
Entry(tk,textvariable = username).grid(row=0,column=1,padx=10,pady=10)
Entry(tk,textvariable = path1).grid(row=1,column=1)
Entry(tk,textvariable = default).grid(row=2,column=1)
#多选框插件
button=Checkbutton(tk,text="请谨慎使用",variable=var)
button.grid(row=3,columnspan=2,sticky=W)
#插入图片
photo=PhotoImage(file="python.png")
label=Label(image=photo)
label.grid(row=0,column=2,rowspan=2,columnspan=2,
sticky=W+E+N+S, padx=5, pady=5)#合并两行,两列,居中,四周外延5个长度
#按钮控件
button1=Button(tk,text="上传文件")
button1.grid(row=3,column=2,sticky=E)
button2=Button(tk,text="下载文件")
button2.grid(row=3,column=3,sticky=E)
#主事件循环
mainloop()