实训之压缩软件

# 压缩文件

import tkinter
import tkinter.filedialog
import tkinter.messagebox
import zipfile
import os


class ZipDemo:
def __init__(self):
self.root = tkinter.Tk()
self.root.minsize(300, 400)
self.root.title('chy压缩软件')
self.showLabel()
self.root.mainloop()
self.files = ()
self.root.resizable(width = False, height = False)


# 添加文件
def selectFiles(self):
# 全局变量
global files
self.files = tkinter.filedialog.askopenfilenames(title='请选择要压缩的文件')
print(self.files)
# 临时路径
self.tmpfiles = []
# 遍历元祖 进行路径的截取
for i in self.files:
# 判断路径字符个数是否超过长度
if len(i) >= 40:
i = i[0:15] + '...' + i[-15:]
# 将处理之后的数据存入临时列表
self.tmpfiles.append(i)

# 将所有文件路径组成字符串 写入label
filestr = '\n'.join(self.tmpfiles)
print(filestr)
self.filenames.set(filestr)

# 压缩文件
def zipFiles(self):
# 全局声明
global files
# 获取压缩文件路径
self.filename = tkinter.filedialog.asksaveasfilename(title='请选择压缩路径',filetypes=(('zip 文件', '*.zip'), ('doc 文件', '*.doc')))
# 新建压缩文件
self.zp = zipfile.ZipFile(self.filename,'a')
# 遍历文件信息
for onefile in self.files:
self.zp.write(onefile, os.path.basename(onefile))
# 关闭压缩文件
self.zp.close()
# 提示用户压缩路径
tkinter.messagebox.showinfo(title = '操作结果',message='提示压缩成功:' + self.filename )

# 解压
def jyFiles(self):
# 选择压缩文件
jypath = tkinter.filedialog.askopenfilename(title='选择解压文件', filetypes=[('zip 文件', '*.zip')])
# 解压路径
zippath = tkinter.filedialog.askdirectory(title='选择解压路径')
print(zippath, type(zippath))
zf = zipfile.ZipFile(jypath, 'r')
zf.extractall(zippath)
# 弹出提示框
tkinter.messagebox.showinfo('提示', '解压成功,解压路径:' + zippath)

# 界面布局
def showLabel(self):
# 添加文件按钮
btn1 = tkinter.Button(self.root, text='添加文件', fg='blue', command=self.selectFiles)
btn1.place(x=20, y=20, width=80, height=40)

# 添加压缩按钮
btn2 = tkinter.Button(self.root, text='压缩文件', fg='red', command=self.zipFiles)
btn2.place(x=110, y=20, width=80, height=40)

# 添加解压按钮
btn3 = tkinter.Button(self.root, text='解压文件', fg='black', command=self.jyFiles)
btn3.place(x=205, y=20, width=80, height=40)
# 声明label使用的变量
self.filenames = tkinter.StringVar()
self.filenames.set('当前没有文件')
# 显示信息的组建
label = tkinter.Label(self.root, bg='white', textvariable=self.filenames, justify='left', anchor='w')
label.place(x=15, y=80, width=270, height=300)


zip = ZipDemo()

原文地址:https://www.cnblogs.com/cuihengyue/p/7906516.html