You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于Tkinter的JSON文件可视化编辑与导出GUI开发问题

Tkinter JSON编辑器实现方案

一、核心功能实现步骤

1. 搞定JSON文件上传

用Tk自带的文件选择框选JSON文件,读取后解析成Python数据结构,兼容单条字典或多条字典列表的格式。

2. 动态生成输入控件

每条原始JSON数据对应一行,左边显示原始内容,中间放备注输入框,右边放Sector下拉菜单,把控件和数据绑定好,方便后续取值。

3. 提交并导出更新后的JSON

遍历所有输入控件,把用户输入的内容加到原始JSON数据里,再导出成新的JSON文件,保留所有原字段。


完整可运行代码

import tkinter as tk
from tkinter import filedialog, ttk, messagebox
import json

class JSONEditor:
    def __init__(self, root):
        self.root = root
        self.root.title("JSON信息补全工具")
        
        # 存原始JSON数据
        self.origin_data = []
        # 存控件和数据的对应关系
        self.control_map = []
        
        # 顶部按钮栏
        top_frame = ttk.Frame(root)
        top_frame.pack(pady=10, fill=tk.X, padx=10)
        
        ttk.Button(top_frame, text="上传JSON文件", command=self.load_json).pack(side=tk.LEFT, padx=5)
        self.submit_btn = ttk.Button(top_frame, text="提交导出", command=self.save_json, state=tk.DISABLED)
        self.submit_btn.pack(side=tk.RIGHT, padx=5)
        
        # 表格展示区
        self.tree = ttk.Treeview(root, columns=("原始数据", "备注", "Sector"), show="headings")
        self.tree.heading("原始数据", text="原始JSON内容")
        self.tree.heading("备注", text="手动输入备注")
        self.tree.heading("Sector", text="选择Sector")
        
        self.tree.column("原始数据", width=300)
        self.tree.column("备注", width=150)
        self.tree.column("Sector", width=150)
        
        self.tree.pack(fill=tk.BOTH, expand=True, padx=10, pady=5)
        
    def load_json(self):
        # 选文件
        file_path = filedialog.askopenfilename(filetypes=[("JSON文件", "*.json")])
        if not file_path:
            return
        
        # 读JSON
        try:
            with open(file_path, "r", encoding="utf-8") as f:
                self.origin_data = json.load(f)
            # 转成列表格式,统一处理
            if isinstance(self.origin_data, dict):
                self.origin_data = [self.origin_data]
        except json.JSONDecodeError:
            messagebox.showerror("出错了", "这个JSON文件格式不对!")
            return
        
        # 清空旧内容
        for item in self.tree.get_children():
            self.tree.delete(item)
        self.control_map.clear()
        
        # 生成每行的控件
        sector_list = ["科技", "金融", "医疗", "制造业", "其他"]  # 可自己改选项
        for idx, data in enumerate(self.origin_data):
            # 插入原始数据行
            row_id = self.tree.insert("", tk.END, values=(str(data), "", ""))
            
            # 备注输入框
            note_entry = ttk.Entry(self.root)
            self.tree.window_create(row_id, column="备注", window=note_entry)
            
            # Sector下拉菜单
            sector_var = tk.StringVar()
            sector_combo = ttk.Combobox(self.root, textvariable=sector_var, values=sector_list, state="readonly")
            self.tree.window_create(row_id, column="Sector", window=sector_combo)
            
            # 存控件和数据索引的对应关系
            self.control_map.append({
                "idx": idx,
                "note": note_entry,
                "sector": sector_var
            })
        
        # 启用提交按钮
        self.submit_btn.config(state=tk.NORMAL)
        
    def save_json(self):
        # 更新原始数据
        for item in self.control_map:
            idx = item["idx"]
            note_text = item["note"].get().strip()
            sector_text = item["sector"].get()
            
            # 把新内容加到原数据里
            self.origin_data[idx]["备注"] = note_text
            self.origin_data[idx]["Sector"] = sector_text
        
        # 选保存路径
        save_path = filedialog.asksaveasfilename(defaultextension=".json", filetypes=[("JSON文件", "*.json")])
        if not save_path:
            return
        
        # 写入文件
        try:
            with open(save_path, "w", encoding="utf-8") as f:
                json.dump(self.origin_data, f, ensure_ascii=False, indent=4)
            messagebox.showinfo("搞定", "文件已经导出成功啦!")
        except Exception as e:
            messagebox.showerror("出错", f"导出失败:{str(e)}")

if __name__ == "__main__":
    root = tk.Tk()
    app = JSONEditor(root)
    root.geometry("700x500")
    root.mainloop()

重点说明

  • 文件上传:自动识别JSON格式,要是文件坏了会弹提示,还能兼容单条数据和多条数据的JSON。
  • 控件绑定:每条数据的输入控件都和数据索引存一起,提交时不会搞混对应关系。
  • 数据保留:直接在原始JSON数据的字典里加新字段,原来的所有内容都不会丢。
  • 导出设置:导出的JSON会自动排版,中文不会变成乱码的Unicode字符。

自定义调整点

  • 下拉菜单的选项可以改sector_list里的内容,加自己需要的分类。
  • 列宽可以调整self.tree.column里的width值,适配你的数据长度。

内容的提问来源于stack exchange,提问作者FruitSnacks19

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 20:05:28