【问题标题】:UnboundLocalError: local variable 'file1' referenced before assignment please help to fixUnboundLocalError:分配前引用了局部变量“file1”,请帮助修复
【发布时间】:2021-09-24 16:53:35
【问题描述】:

我需要在单击按钮时将 file_name 变量保存到文件中。请告诉我如何修复我的代码:

window = tk.Tk()
window.title("Open")
window.geometry("600x400")
window.resizable(False, False)

file_name = ""


def openu():
    global file_name
    if file_name == "":
        file_name = tfd.askopenfilename()
        with open("Filen.json", "w") as file1:
            json.dump(file_name, file1, indent=2, ensure_ascii=False)
        os.startfile(file_name)
    else:
        with open("Filen.json", "r") as file1:
            json.load(file1)
        os.startfile(file_name)
    if btn1["text"] == "":
        btn1["text"] = file_name


btn1 =  tk.Button(window, text="", command=openu)
btn1.place(x = 20, y = 25)



window.mainloop()

更新: 当您单击该按钮时,程序会打开一个打开文件的对话框。一个 File.json 被创建。一切都显示出来了,但有一件事不起作用。我需要在重新启动程序时,按钮不为空。我改了代码,放了完整的。

【问题讨论】:

  • 如果 file_name 为空字符串,则永远不会定义 file1
  • @JohnGordon 请稍等,我现在将重新提出问题。
  • 通过更改此代码,该错误不再发生。如果您仍然收到错误,那么您的真实代码必须与您在此处显示的不同。
  • @JohnGordon 此代码创建一个文件,打开按钮上指定的文件,但不从 File.json 加载结果。还有错误:TypeError:JSON 对象必须是 str、bytes 或 bytearray,而不是 TextIOWrapper
  • 我不明白你遇到了什么问题。请说明该程序在做什么,以及它与您想要的有何不同。否则我只是猜你的意思。

标签: python json


【解决方案1】:

这里是代码。当用户打开窗口时,它会从 json 文件中加载文件路径并自动设置按钮的文本。当用户按下按钮时,它会要求一个新的文件路径名。更详细的解释可以在代码中的cmets中找到。

import tkinter as tk
import tkinter.filedialog as tfd
import json
import os

window = tk.Tk()
window.title("Open")
window.geometry("600x400")
window.resizable(False, False)

file_name = ""

def load_json():
    global file_name

    # Load the json file if it exists
    if os.path.exists("Filen.json"):
        with open("Filen.json") as file1:
            contents = json.load(file1)

            # If the json has a path in it, load the path to file_name
            # Otherwise, set file_name to an empty string ""
            if len(contents) > 0:
                if contents[0] != "":
                    file_name = contents[0]
                else:
                    file_name = ""
            else:
                file_name = ""

    # Create the json file if it does not exist
    else:
        with open("Filen.json", "w") as file1:
            json.dump([file_name], file1, indent=2, ensure_ascii=False)

def openu():
    global file_name

    # Load the json file
    load_json()

    # If file_name is still "", ask the user to input a file path
    path = tfd.askopenfilename()

    # If the user gave a path (did not hit Cancel), save path to file_name
    # and set the button's label
    if path != ():
        file_name = path

        btn1.config(text=file_name)

        # Save file_name to the json file
        with open("Filen.json", "w") as file1:
            json.dump([file_name], file1, indent=2, ensure_ascii=False)

# Load the json file, and put the file name into the button's text
load_json()
btn1 =  tk.Button(window, text=file_name, command=openu)
btn1.place(x = 20, y = 25)

window.mainloop()

【讨论】:

    猜你喜欢
    • 2020-08-13
    • 1970-01-01
    • 2013-07-19
    • 2016-02-10
    • 1970-01-01
    • 2017-08-10
    • 2020-01-16
    • 2019-12-05
    • 2017-09-19
    相关资源
    最近更新 更多