对于PySimpleGUI进度条的使用

前言 

我之前写了一个alive_progress应用的文章,但我发现使用命令台的进度条不适合对于客户端的使用,我之前是知道PySide2或PyQt5的Creater可以自定义一个进度条,但我搞来搞去,发现我把它的进度到100%时不晓得如何关闭界面,于是我就在网上找了一大圈,最终发现只有PySimpleGUI可以方便地调用,我在这里就如何使用这个进度条做一个解说。

原代码

废话不多说,我们直接上代码

​
import os
import shutil
from shutil import move
from tkinter.filedialog import askopenfilename as fe
from webbrowser import open as op
from time import sleep, time
import matplotlib
import matplotlib.pyplot as plt
from PIL import Image, ImageDraw, ImageSequence
import PySimpleGUI as sg

scale = 7.4
bs = 1
width = 0
height = 0
total = 0
sum = 0
img_colorchars = []
inl = 0
matplotlib.use('TKAgg')
# 图片宽高
file1 = fe(title='请选择要处理的图片')
file1 = fr'{file1:s}'

t1 = time()
t2 = time()

def img2char(imgobj):
    global width, height, total, lst, inl, bs
    # 灰度图
    img_original = imgobj
    width, height = (imgobj.width, imgobj.height)
    img = imgobj.convert('L')
    plt.rcParams['image.cmap'] = 'gray'

    # 70 level 字符串
    ASCII_HIGH = r'''$@B%8&WM##oahkbdpqwmZO0QLCJUYXzcvunxrjft/\|()1{}[]?-_+~<>i!lI;:,\"^`'. '''
    # 创建画布
    img_new = Image.new('RGB', (int(width * scale), int(height * scale)), 'white')
    draw = ImageDraw.Draw(img_new)
    total += 1
    # 灰度图转字符串
    for y in range(1, height+1):
        for x in range(1, width+1):
            h = height - 1
            w = width - 1
            t2 = time()
            pos = ((x - 1), (y - 1))
            gray = img.getpixel(pos)  # 0-255
            index = int(gray / 256 * 70)
            txt = ASCII_HIGH[index] + ' '
            color = img_original.getpixel(((x - 1) * bs, (y - 1) * bs))
            draw.text(((x - 1) * scale, (y - 1) * scale), txt, fill=color)
    return img_new

def gif2char(imgfile):
    global sum, img_colorchars, t2, t1, lst, inl
    img = Image.open(imgfile)
    # 分帧操作
    frames = ImageSequence.Iterator(img)
    f = ImageSequence.Iterator(img)
    # 记录图片的帧数
    for i in f:
        sum += 1
    # 保存转换好的字符画
    for frame in frames:
        # 静态图转字符画
        colorchar = img2char(frame)
        img_colorchars.append(colorchar)
    inl += 1
    print()
    # 合成gif
    try:
        if '/' in file1:
            new_file = file1.split('/')
        elif '\\' in file1:
            new_file = file1.split('//')
        if sum == 1:
            new_file_name = list(os.path.splitext(
                new_file[len(new_file) - 1]))[0] + '2.png'
        else:
            new_file_name = list(os.path.splitext(
                new_file[len(new_file) - 1]))[0] + '2.gif'
        for i in range(len(img_colorchars)):
            img_colorchars[i].resize((width, height))
        img_colorchars[0].save(new_file_name,
                               append_images=img_colorchars[1:],
                               loop=0,
                               save_all=True)
        move(new_file_name, os.path.dirname(file1))
        print('图像处理成功!')
        op(os.path.dirname(file1) + '\\' + new_file_name)
        return img_colorchars
    except shutil.Error:
        os.remove(os.path.dirname(file1) + '\\' + new_file_name)
        move(new_file_name, os.path.dirname(file1))
        print('图像处理成功!')
        op(os.path.dirname(file1) + '\\' + new_file_name)
        return img_colorchars


def main():
    gif2char(file1)
    sleep(5)


if __name__ == '__main__':
    main()

​

开始添加

这个库要求要有一个计数器,我就搞了半天搞出来了表示“现在是第几个”的变量。这里怎么做出来的就不多说了。

cnt = (y - 2) * w + x + (total - 1) * h * w-1

我们在开头添加PySimpleGUI的库,然后在55行后添加进度条的函数

import PySimpleGUI as sg
···
cnt = (y - 2) * w + x + (total - 1) * h * w-1
            sg.one_line_progress_meter(
                '正在处理中',
                cnt+1,
                h * w * sum,
                orientation='h',
                bar_color=('#00FF00', '#FFFFFF')
            )

第一个参数是进度条的标题,第二个是计数器cnt的值每次要增加几,第三个是进度条数值的总数,第四个是要水平还是垂直,水平为h,垂直为w,默认为w,最后一个是进度条的颜色,第一个是其本身的颜色,第二个是没处理完的部分。我使用的是windows系统,就比较喜欢绿色的。

完整代码

import os
import shutil
from shutil import move
from tkinter.filedialog import askopenfilename as fe
from webbrowser import open as op
from time import sleep, time
import matplotlib
import matplotlib.pyplot as plt
from PIL import Image, ImageDraw, ImageSequence
import PySimpleGUI as sg

scale = 7.4
bs = 1
width = 0
height = 0
total = 0
sum = 0
img_colorchars = []
inl = 0
matplotlib.use('TKAgg')
# 图片宽高
file1 = fe(title='请选择要处理的图片')
file1 = fr'{file1:s}'

t1 = time()
t2 = time()

def img2char(imgobj):
    global width, height, total, lst, inl, bs
    # 灰度图
    img_original = imgobj
    width, height = (imgobj.width, imgobj.height)
    img = imgobj.convert('L')
    plt.rcParams['image.cmap'] = 'gray'

    # 70 level 字符串
    ASCII_HIGH = r'''$@B%8&WM##oahkbdpqwmZO0QLCJUYXzcvunxrjft/\|()1{}[]?-_+~<>i!lI;:,\"^`'. '''
    # 创建画布
    img_new = Image.new('RGB', (int(width * scale), int(height * scale)), 'white')
    draw = ImageDraw.Draw(img_new)
    total += 1
    # 灰度图转字符串
    for y in range(1, height+1):
        for x in range(1, width+1):
            h = height - 1
            w = width - 1
            t2 = time()
            pos = ((x - 1), (y - 1))
            gray = img.getpixel(pos)  # 0-255
            index = int(gray / 256 * 70)
            txt = ASCII_HIGH[index] + ' '
            color = img_original.getpixel(((x - 1) * bs, (y - 1) * bs))
            draw.text(((x - 1) * scale, (y - 1) * scale), txt, fill=color)
            cnt = (y - 2) * w + x + (total - 1) * h * w-1
            sg.one_line_progress_meter(
                '正在处理中',
                cnt+1,
                h * w * sum,
                orientation='h',
                bar_color=('#00FF00', '#FFFFFF')
            )
    return img_new

def gif2char(imgfile):
    global sum, img_colorchars, t2, t1, lst, inl
    img = Image.open(imgfile)
    # 分帧操作
    frames = ImageSequence.Iterator(img)
    f = ImageSequence.Iterator(img)
    # 记录图片的帧数
    for i in f:
        sum += 1
    # 保存转换好的字符画
    for frame in frames:
        # 静态图转字符画
        colorchar = img2char(frame)
        img_colorchars.append(colorchar)
    inl += 1
    print()
    # 合成gif
    try:
        if '/' in file1:
            new_file = file1.split('/')
        elif '\\' in file1:
            new_file = file1.split('//')
        if sum == 1:
            new_file_name = list(os.path.splitext(
                new_file[len(new_file) - 1]))[0] + '2.png'
        else:
            new_file_name = list(os.path.splitext(
                new_file[len(new_file) - 1]))[0] + '2.gif'
        for i in range(len(img_colorchars)):
            img_colorchars[i].resize((width, height))
        img_colorchars[0].save(new_file_name,
                               append_images=img_colorchars[1:],
                               loop=0,
                               save_all=True)
        move(new_file_name, os.path.dirname(file1))
        print('图像处理成功!')
        op(os.path.dirname(file1) + '\\' + new_file_name)
        return img_colorchars
    except shutil.Error:
        os.remove(os.path.dirname(file1) + '\\' + new_file_name)
        move(new_file_name, os.path.dirname(file1))
        print('图像处理成功!')
        op(os.path.dirname(file1) + '\\' + new_file_name)
        return img_colorchars


def main():
    gif2char(file1)
    sleep(5)


if __name__ == '__main__':
    main()

最终效果

你可能感兴趣的:(Python,matplotlib,python,开发语言)