吾爱破解 - LCG - LSG |安卓破解|病毒分析|www.52pojie.cn

 找回密码
 注册[Register]

QQ登录

只需一步,快速开始

查看: 1433|回复: 1
收起左侧

[Python 原创] 【原创源码】【Python】PyQt5Json格式文本与字典格式文本相互转换

[复制链接]
过去的回忆 发表于 2020-7-27 10:05
python中的字典格式是可以使用单引号, 在线的json格式化不支持单引号,所以写了个相互转换的pyqt5小例子(作为练习)。
最近刚学pyqt5,不足的地方敬请见谅。
[Python] 纯文本查看 复制代码
import sys, jsonfrom PyQt5.QtWidgets import (QWidget, QApplication, QHBoxLayout, QVBoxLayout, QPushButton, QTextEdit, QLabel,
                             QMessageBox)


class JsonToDict(QWidget):

    def __init__(self, parent=None):
        super(JsonToDict, self).__init__(parent)
        self.initUI()

    def initUI(self):

        self.setGeometry(300, 300, 600, 300)
        self.setWindowTitle('JsonToDict')

        json_label = QLabel('json文本')
        self.json_text_edit = QTextEdit(self)
        dict_label = QLabel('dict文本')
        self.dict_text_edit = QTextEdit(self)

        json_layout = QHBoxLayout()  # 将label和textEdit横向布局
        json_layout.addWidget(json_label)
        json_layout.addWidget(self.json_text_edit)

        dict_layout = QHBoxLayout()
        dict_layout.addWidget(dict_label)
        dict_layout.addWidget(self.dict_text_edit)

        json_btn = QPushButton('json_to_dict')
        json_btn.clicked.connect(self.json_click)  # 添加点击事件
        dict_btn = QPushButton('dict_to_json')
        dict_btn.clicked.connect(self.dict_click)  # 添加点击事件
        clear_btn = QPushButton('清空')
        clear_btn.clicked.connect(self.clear_click)  # 添加点击事件

        btn_layout = QHBoxLayout()  # 将button横向布局
        btn_layout.addWidget(json_btn)
        btn_layout.addWidget(dict_btn)
        btn_layout.addWidget(clear_btn)

        overall_layout = QVBoxLayout()  # 整体竖向布局
        overall_layout.addLayout(json_layout)
        overall_layout.addLayout(dict_layout)
        overall_layout.addLayout(btn_layout)

        self.setLayout(overall_layout)

        self.show()

    def json_click(self):
        json_content = self.json_text_edit.toPlainText()
        try:
            self.dict_text_edit.setText(str(json.loads(json_content)))
        except Exception as e:
            QMessageBox.critical(self, "错误", "输入有误!")

    def dict_click(self):
        dict_content = self.dict_text_edit.toPlainText()
        try:
            self.json_text_edit.setText(json.dumps(eval(dict_content)))
        except Exception as e:
            QMessageBox.critical(self, "错误", "输入有误!")

    def clear_click(self):
        self.json_text_edit.clear()
        self.dict_text_edit.clear()


if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = JsonToDict()
    sys.exit(app.exec_())


1.jpg
2.jpg
3.jpg

发帖前要善用论坛搜索功能,那里可能会有你要找的答案或者已经有人发布过相同内容了,请勿重复发帖。

v.n.lee 发表于 2020-7-27 15:13
json与dic有啥区别吗,没搞懂
您需要登录后才可以回帖 登录 | 注册[Register]

本版积分规则 警告:本版块禁止灌水或回复与主题无关内容,违者重罚!

快速回复 收藏帖子 返回列表 搜索

RSS订阅|小黑屋|处罚记录|联系我们|吾爱破解 - LCG - LSG ( 京ICP备16042023号 | 京公网安备 11010502030087号 )

GMT+8, 2024-6-7 17:40

Powered by Discuz!

Copyright © 2001-2020, Tencent Cloud.

快速回复 返回顶部 返回列表