华为简易压缩算法python_Python(9) --实现一个简单的压缩软件/解压软件的功能
#壓縮軟件
#導入所需模塊,設置界面
import os
import zipfile
import tkinter
import tkinter.messagebox
import tkinter.filedialog
root = tkinter.Tk()
root.title('我的壓縮軟件')
root.minsize(300,400)
#設置需要壓縮文件的路徑變量
filenames = []
#添加文件的函數
def addfiles():
#全局化變量
global filenames
#彈出文件選擇對話框,選擇需要添加的文件
files = tkinter.filedialog.askopenfilenames()
#將選擇的文件添加到列表filenames中
filenames += list(files)
#將列表中的數據連接成字符串
strs = '\n'.join(filenames)
#將需要壓縮文件的路徑寫入標簽中顯示
label['text'] = strs
#判斷是否添加了文件,顯示添加文件的個數
global num
num = strs.count('\n') + 1
if filenames == []:
tkinter.messagebox.showinfo(title='提示信息', message='您好,您還未添加任何文件')
else:
tkinter.messagebox.showinfo(title='提示信息', message='您好,您共添加了{}個文件'.format(num))
#壓縮文件的函數
def zip_files():
#創(chuàng)建壓縮文件的目錄變量
global path
path = './myzip.zip'
#提示是否需要對當前文件進行壓縮
result = tkinter.messagebox.askokcancel(title='提示信息', message='是否需要對當前{}個文件進行壓縮?'.format(num))
#根據用戶選擇是否需要創(chuàng)建壓縮文件
if result == True:
# 創(chuàng)建壓縮文件
zp = zipfile.ZipFile(path, 'w')
# 向壓縮文件中添加文件內容
#遍歷添加文件的列表
for file in filenames:
global dir
dir = os.path.basename(file)
zp.write(file,dir)
# 關閉壓縮文件
zp.close()
#判斷壓縮文件是否創(chuàng)建成功
if os.path.exists(path):
tkinter.messagebox.showinfo(title = '提示信息',message = '壓縮文件創(chuàng)建成功!!!\n目錄為:'+ path)
else:
tkinter.messagebox.showerror(title = '錯誤信息',message = '壓縮文件創(chuàng)建失敗!!!')
#解壓文件的函數
def unzip_files():
try:
# 選擇解壓文件夾
tkinter.messagebox.showinfo(title='提示信息', message='請選擇選擇解壓文件!!!')
unzipfile = tkinter.filedialog.askopenfilename()
#提示用戶是否解壓當前文件
result = tkinter.messagebox.askokcancel(title='提示信息', message='是否需要對當文件進行解壓?')
if result == True:
# 選擇解壓的路徑
tkinter.messagebox.showinfo(title='提示信息', message='請選擇選擇解壓路徑!!!')
unzippath = tkinter.filedialog.askdirectory()
# 打開解壓文件夾
unzp = zipfile.ZipFile(unzipfile)
# 解壓所有文件
unzp.extractall(unzippath)
# 關閉壓縮文件
unzp.close()
tkinter.messagebox.showinfo(title='提示信息', message='解壓文件成功!!!')
else:
tkinter.messagebox.showinfo(title='提示信息', message='您已取消解壓,\n解壓文件失敗!!!')
# 判斷解壓是否成功
except:
tkinter.messagebox.showerror(title='錯誤信息', message='系統(tǒng)程序錯誤,\n解壓文件失敗!!!')
#擺放按鈕組件
btn_add = tkinter.Button(root,text = '添加文件',command = addfiles)
btn_add.place(x = 10,y = 20 )
btn_zip = tkinter.Button(root,text = '壓縮文件',command = zip_files)
btn_zip.place(x = 110,y = 20)
btn_unzip = tkinter.Button(root,text = '解壓文件',command = unzip_files)
btn_unzip.place(x = 210,y = 20)
#顯示信息區(qū)域
label = tkinter.Label(root,text = '暫時沒有文件信息',bg = 'white',anchor = 'nw',justify = 'left')
label.place(x = 10,y = 70 ,width = 280,height = 300)
root.mainloop()
創(chuàng)作挑戰(zhàn)賽新人創(chuàng)作獎勵來咯,堅持創(chuàng)作打卡瓜分現金大獎總結
以上是生活随笔為你收集整理的华为简易压缩算法python_Python(9) --实现一个简单的压缩软件/解压软件的功能的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python怎么导入os模块_pytho
- 下一篇: linux sh 编程,Linux sh