Python+PySimpleGUI+Pyinstaller,制作JSON格式化小工具

本文介绍了如何在Python3.9环境中利用PyCharm开发一个简单的JSON格式化工具,通过PySimpleGUI设计用户界面,以及如何使用PyInstaller将程序打包成可执行文件。开发者展示了如何处理JSON输入、格式化和异常情况,并提供了代码示例和EXE文件下载链接。
摘要由CSDN通过智能技术生成

开发环境

Python3.9+PyCharm

第三方库

pip install PySimpleGUI

pip install Pyinstaller

pip install json

json处理逻辑:JSONmessage.py

import json

def get_formated(json_str):
    try:
        try:
            date = json.loads(json_str)     #接受双引号json
            json_data = json.dumps(date, indent=4, ensure_ascii=False)   #json格式化
            color = "black"   #字体颜色黑色
            return json_data, color
        except Exception as e:
            date = eval(json_str)      #接受单引号json
            json_data = json.dumps(date, indent=4, ensure_ascii=False)    #json格式化
            color = "black"   #字体颜色黑色
            return json_data, color

    except Exception as e:
        json_data = "JSON输入值错误,请检查后重新输入,错误信息如下\n"       #异常处理
        json_data += str(e)
        color = "red"   #字体颜色红色
        return json_data, color

设计UI布局并关联处理逻辑:JSON格式化工具.py

import PySimpleGUI
import JSONmessage

def formattedjeson():
    # ui布局
    layout = [
        [PySimpleGUI.Text("输入值:", font=("宋体", 15))],
        [PySimpleGUI.Multiline(key="Input", size=(100, 10))],
        [PySimpleGUI.Button("执行格式化", expand_x=True)],
        [PySimpleGUI.Text("输出值:", font=("宋体", 15))],
        [PySimpleGUI.Multiline(key="Output", size=(100, 15))]
    ]
    windows = PySimpleGUI.Window("JSON格式化工具", layout)
    while True:
        event, values = windows.read()
        if event == PySimpleGUI.WIN_CLOSED:
            windows.close()
            break
        if event == '执行格式化':
            print('layout', layout)
            test2 = layout[1][0].get()    #获取要格式化json
            print('test2', test2)
            test2 = JSONmessage.get_formated(test2)   #格式化json
            print('test2', test2)
            windows["Output"].update(
                value=test2[0],  # str更新文本(只更新文本可以智驾用字符串)
                background_color=None,  # 更新文本背景颜色
                text_color=test2[1],  # 更新文本颜色
                visible=None  # 更新元素的可见状态
            )


formattedjeson()

Pyinstaller命令生成Windows小工具

命令行输入:Pyinstaller -F -w  JSON格式化工具.py

双击后打开

格式化一个json试试

最后这exe文件可以放在任何一个win电脑运行

代码源文件和EXE样例

https://download.csdn.net/download/weixin_43389186/89066525icon-default.png?t=N7T8https://download.csdn.net/download/weixin_43389186/89066525

  • 11
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值