Py学习  »  Python

用Python制作可视化GUI界面,顺便实现自动分类整理文件!

Python开发 • 2 年前 • 319 次点击  
👇👇关注后回复 “进群” ,拉你进程序员交流群👇👇

作者丨阿尔卑斯、黄同学

来源丨快学Python


有时候,我们写了一些简单、有用的小代码。此时,如果能够有一个可视化GUI界面,是不是显得很舒服。今天介绍的一个Python库,超级牛逼,几行代码就可以实现一个可视化界面!

Gooey介绍

这里用到的是一个第三方包Gooey,它只需要一行代码,就可以将Python程序,转换为图形界面应用【加上装饰器函数, 额外添加几个参数就可以了】

Gooey是一个Python GUI程序开发框架,基于wxPython GUI库,使用方法类似于Python内置CLI开发库 argparse,用一行代码即可快速将控制台程序,转换为GUI应用程序。

官方地址:https://github.com/chriskiehl/Gooey

① 安装方式

pip install Gooey

② 一个简单的例子

Gooey 通过将一个简单的装饰器附加到主函数上,然后使用GooeyParser可将你所有需要用到的参数,可视化为文本框选择框甚至是文件选择框

from gooey import Gooey, GooeyParser

@Gooey
def main():
    parser = GooeyParser(description="My GUI Program!")
  parser.add_argument('Filename', widget="FileChooser")      # 文件选择框
 parser.add_argument('Date', widget="DateChooser")          # 日期选择框
 args = parser.parse_args()                                 # 接收界面传递的参数
 print(args)

if   __name__ == '__main__':
    main()

结果如下:

我们还可以通过将参数传递给装饰器,来配置不同的样式功能

@Gooey(advanced=Boolean,          # toggle whether to show advanced config or not 
       language=language_string,  # Translations configurable via json
       auto_start=True,           # skip config screens all together
       target=executable_cmd,     # Explicitly set the subprocess executable arguments
       program_name='name',       # Defaults to script name
       program_description,       # Defaults to ArgParse Description
       default_size=(610, 530),   # starting size of the GUI
       required_cols=1,           # number of columns in the "Required" section
       optional_cols=2,           # number of columns in the "Optional" section
       dump_build_config=False,   # Dump the JSON Gooey uses to configure itself
       load_build_config=None,    # Loads a JSON Gooey-generated configuration
       monospace_display=False)   # Uses a mono-spaced font in the output screen
)

上面已经使用了两个简单的控件:FileChooserDateChooser·,分别提供了“文件选择器”和 “日期选择器”的功能。Gooey 中,现在支持的 chooser 类控件有:

配置参数主要是对Gooey界面做全局配置,配置方法如下:

@Gooey(program_name='Demo')
def function():
    pass

和program_name参数配置一样,Gooey 还支持很多其它配置,下面是它支持的参数列表:

案例介绍

比如我们想做一个文件整理的自动化程序,如图所示,有这样一堆杂乱地文件,我们需要将相同类型地文件进行分类。

此时可以思考一下,可视化界面上需要有一个文件选择框,我们选择好对应文件夹之后,点击开始,就可以实现最终的文件分类,岂不美哉?

那么如何使用这个库实现这个功能呢?

# 导入相关库
import os
import glob
import shutil
from gooey import Gooey, GooeyParser

# 定义一个文件字典,不同的文件类型,属于不同的文件夹,一共9个大类。
file_dict = {
    '图片': ['jpg''png''gif''webp'],
    '视频': ['rmvb''mp4''avi''mkv''flv'],
    "音频" : ['cd''wave''aiff''mpeg''mp3''mpeg-4'],
    '文档': ['xls''xlsx''csv''doc''docx''ppt''pptx''pdf''txt'],
    '压缩文件': ['7z''ace''bz''jar''rar''tar''zip''gz'],
    '常用格式': ['json''xml''md''ximd'],
    '程序脚本': ['py''java''html''sql''r''css''cpp''c''sas''js''go'],
    '可执行程序': ['exe''bat''lnk''sys''com'],
    '字体文件': ['eot''otf''fon''font''ttf''ttc''woff''woff2']
}


# 定义一个函数,传入每个文件对应的后缀。判断文件是否存在于字典file_dict中;
# 如果存在,返回对应的文件夹名;如果不存在,将该文件夹命名为"未知分类";
def func(suffix):
    for name, type_list in file_dict.items():
        if suffix.lower() in type_list:
            return name
    return "未知分类"


@Gooey(encoding='utf-8', program_name="整理文件小工具-V1.0.0\n\n公众号:数据分析与统计学之美", language='chinese')
def start():
    parser = GooeyParser()
    parser.add_argument("path"help="请选择要整理的文件路径:", widget="DirChooser")  # 一定要用双引号 不然没有这个属性
    args = parser.parse_args()
    # print(args, flush=True)  # 坑点:flush=True在打包的时候会用到
    return args


if __name__ == '__main__':
    args = start()
    path = args.path

    # 递归获取 "待处理文件路径" 下的所有文件和文件夹。
    for file in glob.glob(f"{path}/**/*", recursive=True):
        # 由于我们是对文件分类,这里需要挑选出文件来。
        if os.path.isfile(file):
            # 由于isfile()函数,获取的是每个文件的全路径。这里再调用basename()函数,直接获取文件名;
            file_name = os.path.basename(file)
            suffix = file_name.split(".")[-1]
            # 判断 "文件名" 是否在字典中。
            name = func(suffix)
            # print(func(suffix))
            # 根据每个文件分类,创建各自对应的文件夹。
            if not os.path.exists(f"{path}\\{name}"):
                os.mkdir(f"{path}\\{name}")
            # 将文件复制到各自对应的文件夹中。
            shutil.copy(file, f"{path}\\{name}")

最终效果如下:

仔细观察上述代码,涉及到GUI界面制作的代码,根本没有几行,是不是做一个简单的工具超方便?

注意:上述代码请在Pycharm中实现,貌似和jupyter notebook有冲突,运行报错,你可以尝试一下,如果解决了,麻烦留言告知一下,谢谢!

程序打包

"打包"就用我们最常用的pyinstaller吧!




    
# 安装
pip install pyinstaller

# 打包时执行命令 (其中F为大写,w为小写)
pyinstaller -F Tool.py -w

执行效果如下:

生成的exe文件在目录dist下,双击可用。


-End-

最近有一些小伙伴,让我帮忙找一些 面试题 资料,于是我翻遍了收藏的 5T 资料后,汇总整理出来,可以说是程序员面试必备!所有资料都整理到网盘了,欢迎下载!

点击👆卡片,关注后回复【面试题】即可获取

在看点这里好文分享给更多人↓↓

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/122486
 
319 次点击