python使用tkinter制作图片批量压缩工具

import os
import threading
from tkinter import Tk, Label, Button, Entry, filedialog, messagebox, Text

from PIL import Image
imageExtensions = ['.jpg', '.jpeg', '.png']

def compressImage(image_path, limit):
    try:
        pageSize = os.path.getsize(image_path) / 1024
        showMessage('WARNING', '!!!开始压缩图片:' + image_path)
        while pageSize > limit:
            # 打开图片
            with Image.open(image_path) as img:
                # 获取原始尺寸
                original_size = img.size
                new_height = int(original_size[0] * 0.9)
                new_width = int(new_height * (original_size[0] / original_size[1])) # 保持横纵比

                # 调整图片大小
                resized_img = img.resize((new_width, new_height), Image.ANTIALIAS)
                # 保存调整后的图片
                resized_img.save(image_path)
                pageSize = os.path.getsize(image_path) / 1024

        showMessage('', '!!!压缩成功,图片大小为:'+ str(int(pageSize)) + 'kb')
    except Exception as e:
        showMessage('ERROR', '压缩图片'+ image_path +'出错:' + str(e))


def getImageList():
    try:
        text1.delete(1.0, 'end')
        text1.insert('end', '程序执行情况:\n\n')
        folderPath = input1.get()
        showMessage('WARNING', '将在文件夹:‘' + folderPath + '’中获取图片进行压缩')
        fileList = []
        for file in os.listdir(folderPath):
            fileType = os.path.splitext(file)[1]
            if fileType not in imageExtensions:
                raise ValueError('存在不符合格式的文件:' + file)
            else:
                fileList.append(file)
        showMessage('', '获得图片列表:' + str(fileList))

        limit = int(input2.get())
        showMessage('WARNING', '压缩图片限制为:' + str(limit))
        for oneFile in fileList:
            fullPath = folderPath + '/' + oneFile
            # print(fullPath)
            compressImage(fullPath, limit)
        showMessage('', '全部图片压缩完成')
        messagebox.showinfo('完成', '全部图片压缩完成!')
    except Exception as e:
        showMessage('ERROR', '获取图片列表出错:'+str(e))

def selectFolder(input1):
    """
    打开文件夹选择对话框,并将选择的文件夹路径显示在输入框中
    """
    folder_selected = filedialog.askdirectory()
    if folder_selected:
        input1.delete(0, 'end')  # 清空输入框
        input1.insert(0, folder_selected)  # 插入选择的文件夹路径
    # else:
    #     showMessage('ERROR', '未选择文件夹')
    #     # messagebox.showinfo("提示", "未选择文件夹")

def showMessage(type, comment):
    if type == 'ERROR':
        text1.insert('end', '出错 --- '+ str(comment) +';\n\n')
    elif type == 'WARNING':
        text1.insert('end', '提示 --- '+ str(comment) +';\n\n')
    else:
        text1.insert('end', '成功 --- '+ str(comment) +';\n\n')
    text1.see('end')


def createThread(func, *args):
    t = threading.Thread(target=func, args=args)  # 创建进程
    t.setDaemon(True)  # 守护进程
    t.start()  # 启动进程


if __name__ == '__main__':
    try:
        # 制作tk界面
        tk = Tk()
        tk.title('图片压缩工具')
        tk.geometry("450x300+600+300")
        lab1 = Label(text='文件夹:')
        input1 = Entry(width=40)
        lab1.grid(column=0, row=0, sticky='W', pady=5, padx=5)
        input1.grid(column=1, row=0, sticky='W')

        lab2 = Label(text='请输入压缩限制(KB):')
        input2 = Entry(width=10)
        input2.insert('end', '150')
        lab2.grid(column=0, row=1, sticky='W', pady=5, padx=5)
        input2.grid(column=1, row=1, sticky='W')

        but3 = Button(text='选择文件夹', command=lambda: selectFolder(input1))
        but4 = Button(text='开始压缩', command=lambda: createThread(getImageList))
        but3.grid(column=0, row=2, pady=15, sticky='W', padx=5)
        but4.grid(column=1, row=2, pady=15, sticky='W')

        text1 = Text(height=10, width=60)
        text1.insert('end', '程序执行情况:\n\n')
        text1.grid(column=0, row=3, pady=5, padx=5, columnspan=2)
        tk.mainloop()
    except Exception as e:
        print(str(e))

打包成exe命令pyinstaller --onefile --noconsole xxx.py --noconsole是去除执行d1黑框

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值