ValueError: I/O operation on closed file while trying to write a value to a .txt file

ValueError: I/O operation on closed file while trying to write a value to a .txt file

我想使用 Tkinter 在 python 中编写一个货币追踪器。我希望它的工作方式是会有一个标签,说明我目前有多少钱(它从 .txt 文件中读取),两个按钮“添加”和“减去”,用于添加或减去条目中写入的值从金额(它从 .txt 文件中删除之前的金额并写入一个新金额)。我在写add_value()函数的时候遇到了这个错误:

Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Users\Гриша\AppData\Local\Programs\Python\Python38\lib\tkinter\__init__.py", line 1883, in __call__
    return self.func(*args)
  File "C:/Users/Гриша/PycharmProjects/untitled1/money tracker.py", line 24, in add_value
    f.write(str(new_amt))
ValueError: I/O operation on closed file.

函数如下:

def add_value():
    global value_entry
    global money_lbl
    # Gets the number that was stored previously
    with open('money.txt', 'r') as f:
        amt = f.readline()
    # This should erase the contents of the 'money.txt' file
    with open('money.txt', 'w'):
        pass
    # Writing the new value to the file
    with open('money.txt', 'w+'):
        new_amt = int(amt) + int(value_entry.get())
        f.write(str(new_amt))
        money_lbl.configure(text=str(new_amt))

抱歉,如果我解释过度或者我犯了一些错误英语是第二语言)

您在为其定义的 with 块之外引用 ff 仅在您的第一个 with 块中引用一个打开的文件(甚至在那里它以只读模式打开)。具体来说,您在上一个上下文中缺少 as f 部分:

with open('money.txt', 'w+') as f:
    new_amt = ...

不过,您的代码还有其他问题。例如。第二个 with-block 应该不是必需的。只需直接以 "w" 模式打开您的文件。强烈建议不要使用全局变量,int(amt) 不能保证成功。