#压缩软件
import tkinter
import tkinter.messagebox
import zipfile
import tkinter.filedialog
import os
class zip:
files=()
def __init__(self):
self.root=tkinter.Tk()
self.root.minsize(300,300)
self.root.resizable(width=False,height=False)
self.root.title("压缩软件")
#声明label变量
self.filenames=tkinter.StringVar()
self.show()
self.root.mainloop()
# 界面布局
def show(self):
# 选择文件按钮
btn1 = tkinter.Button(self.root, text="选择文件",font=("隶书",12,"bold"),command=self.addfiles,)
btn1.place(x=15, y=20, width=80, height=50)
# 压缩操作按钮
btn1 = tkinter.Button(self.root, text="压缩操作",font=("隶书",12,"bold"),command=self.zipfiles)
btn1.place(x=110, y=20, width=80, height=50)
# 解压操作按钮
btn1 = tkinter.Button(self.root, text="解压操作",font=("隶书",12,"bold"), command=self.jieyazip)
btn1.place(x=205, y=20, width=80, height=50)
# 显示信息的组件
label = tkinter.Label(self.root, bg="white", textvariable=self.filenames, justify="left", anchor="nw")
label.place(x=20, y=80, width=270, height=180)
#选取文件
def addfiles(self):
# 声明全局变量
#global files
#使用文件对话框
self.files=tkinter.filedialog.askopenfilenames(title="请选择要压缩的文件")
#准备显示信息
tmpfiles=[]
#遍历元组 截取和省略操作
for i in self.files:
#判断路径字符个数是否超过指定长度
if len(i) >= 30:
i=i[0:10]+"......"+ i[-10:]
#将处理之后的数据存入临时列表
tmpfiles.append(i)
#将所有文件路径组成字符串,写入label
self.filenames.set("\n".join(tmpfiles))
#提示添加文件成功
tkinter.messagebox.showinfo(title="添加文件",message="添加文件成功!")
#压缩文件
def zipfiles(self):
global files
#获取压缩文件的路径
self.filename=tkinter.filedialog.asksaveasfilename(title="保存文件",filetypes=(("zip 文件","*.zip"),("所有文件","*.*")))
#新建压缩文件
self.zp=zipfile.ZipFile(self.filename,"a")
#添加要压缩的文件
for i in self.files:
self.zp.write(i,os.path.basename(i))
#关闭压缩文件
self.zp.close()
#提示用户压缩路径
tkinter.messagebox.showinfo(title="操作结果",message="压缩成功:"+self.filename)
#解压文件
def jieyazip(self):
#选择解压文件
self.filepath=tkinter.filedialog.askopenfilename(title="选择解压路径",filetypes=(("zip文件","*.zip"),("所有文件","*.*")))
#选择解压路径
self.zippath=tkinter.filedialog.askdirectory(title="选择解压路径")
#读取解压文件
self.zp=zipfile.ZipFile(self.filepath,"r")
#解压所有
self.zp.extractall(self.zippath)
#关闭文件
#self.zp.close()
#提示用户解压缩消息
tkinter.messagebox.showinfo(title="操作结果",message="解压缩成功"+self.zippath)
#实例化对象
jieya=zip()