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():
    #建立壓縮文件的目錄變量
    global path
    path = './myzip.zip'

    #提示是否須要對當前文件進行壓縮
    result = tkinter.messagebox.askokcancel(title='提示信息', message='是否須要對當前{}個文件進行壓縮?'.format(num))
    #根據用戶選擇是否須要建立壓縮文件
    if result == True:
        # 建立壓縮文件
        zp = zipfile.ZipFile(path, 'w')
        # 向壓縮文件中添加文件內容
        #遍歷添加文件的列表
        for file in filenames:
            global dir
            dir = os.path.basename(file)
            zp.write(file,dir)
        # 關閉壓縮文件
        zp.close()

    #判斷壓縮文件是否建立成功
    if os.path.exists(path):
        tkinter.messagebox.showinfo(title = '提示信息',message = '壓縮文件建立成功!!!\n目錄爲:'+ path)
    else:
        tkinter.messagebox.showerror(title = '錯誤信息',message = '壓縮文件建立失敗!!!')

#解壓文件的函數
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='系統程序錯誤,\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)

#顯示信息區域
label = tkinter.Label(root,text = '暫時沒有文件信息',bg = 'white',anchor = 'nw',justify = 'left')
label.place(x = 10,y = 70 ,width = 280,height = 300)



root.mainloop()
相關文章
相關標籤/搜索