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

使用Tkinter+Pandas加载JSON文件报错求助:UnboundLocalError

解决Tkinter加载JSON时的UnboundLocalError错误

错误原因

你的open_file方法存在两个关键问题:

  • 调用fd.askopenfilename时,参数里直接使用pd.read_json(filenames),此时filenames还未被赋值(askopenfilename尚未返回结果),直接触发局部变量未定义错误
  • askopenfilename没有df这个参数,属于参数误用

修正后的代码

import tkinter as tk
from tkinter import filedialog as fd
from tkinter import messagebox
import pandas as pd

class Myapp():

    def __init__(self):
        self.root = tk.Tk()
        self.root.geometry('650x400')
        self.root.title("JSON Data Tool")
        # 初始化存储数据的实例变量,供全局方法调用
        self.df = None

        # 修复按钮重复赋值问题,每个按钮使用独立变量
        self.load_btn = tk.Button(self.root, text="Load JSON Script", font=("Ubuntu", 9), command=self.open_file)
        self.load_btn.grid(row=1, column=2, padx=(50, 50), pady=(25, 10))
        
        self.run_btn = tk.Button(self.root, text="Run JSON Script", font=("Ubuntu", 9), command=self.run_script)
        self.run_btn.grid(row=2, column=2, padx=(50, 50), pady=(5, 10))
        
        self.save_btn = tk.Button(self.root, text="Save Data", font=("Ubuntu", 9), command=self.save_data)
        self.save_btn.grid(row=3, column=2, padx=(50, 50), pady=(5, 10))

    def open_file(self):
        filetypes = [("Json File", "*.json")] 
        # 先获取用户选择的文件路径
        filename = fd.askopenfilename(title="Open File", filetypes=filetypes)
        # 判断用户是否取消选择
        if not filename:
            return
        try:
            # 用获取到的路径加载JSON数据,存入实例变量
            self.df = pd.read_json(filename)
            messagebox.showinfo("成功", "JSON文件加载完成")
        except Exception as e:
            messagebox.showerror("错误", f"加载失败:{str(e)}")

    def run_script(self):
        # 运行前检查数据是否已加载
        if self.df is None:
            messagebox.showwarning("提示", "请先加载JSON文件")
            return
        # 这里可添加你的业务逻辑,示例:打印数据预览
        print("运行脚本逻辑,数据预览:")
        print(self.df.head())

    def save_data(self):
        # 保存前检查数据是否存在
        if self.df is None:
            messagebox.showwarning("提示", "没有可保存的数据")
            return
        save_path = fd.asksaveasfilename(defaultextension=".csv", filetypes=[("CSV文件", "*.csv"), ("Excel文件", "*.xlsx")])
        if save_path:
            try:
                # 根据后缀选择保存格式
                if save_path.endswith('.csv'):
                    self.df.to_csv(save_path, index=False)
                elif save_path.endswith('.xlsx'):
                    self.df.to_excel(save_path, index=False)
                messagebox.showinfo("成功", "数据保存完成")
            except Exception as e:
                messagebox.showerror("错误", f"保存失败:{str(e)}")

    def generator(self):
        self.report = tk.Toplevel(self.root)
        self.report.geometry("180x200")
        self.report.title("Report Generator")
        self.label = tk.Label(self.report, text="REPORT GENERATOR", font=("Nunito",12))
        self.label.grid(row=0, column=1)

        # CHECKBOX
        self.cek1 = tk.Checkbutton(self.report, text="Golden Sample Result",font=("Ubuntu", 10))
        self.cek1.grid(row=1, column=1)
        self.cek2 = tk.Checkbutton(self.report, text="Curve Boundary",font=("Ubuntu", 10))
        self.cek2.grid(row=2, column=1)
        self.cek3 = tk.Checkbutton(self.report, text="Value Tolerance",font=("Ubuntu", 10))
        self.cek3.grid(row=3, column=1)
        self.cek4 = tk.Checkbutton(self.report, text="Pass/Fail",font=("Ubuntu", 10))
        self.cek4.grid(row=4, column=1)
        self.cek5 = tk.Checkbutton(self.report, text="Statistical Table",font=("Ubuntu", 10))
        self.cek5.grid(row=5, column=1)

        self.button = tk.Button(self.report, text="Generate!", font=("Ubuntu", 9))
        self.button.grid(row=6, column=1, padx=(50, 50), pady=(5, 10))

app = Myapp()
app.root.mainloop()

关键修改说明

  • 调整open_file执行顺序:先获取文件路径,再加载JSON数据,解决变量未定义问题
  • 新增实例变量self.df存储数据,让后续的“Run”和“Save”按钮能直接调用
  • 修复按钮重复赋值问题,避免按钮引用被覆盖
  • 添加错误捕获和用户提示,提升交互友好性
  • 为“Run”和“Save”按钮补充基础逻辑,确保操作前数据已就绪

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 22:47:52