Pandas使用Tkinter打开JSON文件

eimct9ow  于 2023-04-18  发布在  其他
关注(0)|答案(1)|浏览(117)

我想做一个可以使用pandas库加载json文件的gui。我已经做了如下代码。

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

class Myapp():

    def __init__(self):
        self.root = tk.Tk()
        self.root.geometry('650x400')

        # MEASUREMENT
        self.m1 = tk.Button(self.root, text="Load JSON Script", font=("Ubuntu", 9), command=self.open_file)
        self.m1.grid(row=1, column=2, padx=(50, 50), pady=(25, 10))
        self.m1 = tk.Button(self.root, text="Run JSON Script", font=("Ubuntu", 9))
        self.m1.grid(row=2, column=2, padx=(50, 50), pady=(5, 10))
        self.m1 = tk.Button(self.root, text="Save Data", font=("Ubuntu", 9))
        self.m1.grid(row=3, column=2, padx=(50, 50), pady=(5, 10))

    def open_file(self):
        filetypes = [("Json File", "*.json")] 
        filenames = fd.askopenfilename(title="Open File", filetypes=filetypes, df = pd.read_json(filenames))

    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()

但我得到一个如下的错误

UnboundLocalError: local variable 'filenames' referenced before assignment

请帮帮我
按钮加载Json脚本可以使用pandas运行。

m0rkklqb

m0rkklqb1#

askopenfilenames()函数显示一个文件对话框,用于选择多个文件。它以str的形式返回选定的文件名。尝试以下操作:

filenames = fd.askopenfilename(title="Open File", filetypes=filetypes)
df = pd.read_json(filenames)

要了解发生了什么,请添加print

def open_file(self):
        filetypes = [("Json File", "*.json")] 
        filenames = fd.askopenfilename(title="Open File", filetypes=filetypes)
        print("-----------------------------")
        print(filenames)
        print("-------------------------------")
        print(type(filenames))

相关问题