引用函数内 "with open" 块内的变量

Reference a variable that is inside a "with open" block inside a function

def write_lor():
    with open("data.txt", 'r+') as filehandle:
        filecontents = filehandle.readlines()
        filehandle.seek(0)
        new = (int(filecontents[0])+1)
        filehandle.write(str(new))
        filehandle.truncate()

这是一种基本的计数器类型的系统,可以保存到 txt。无论如何要在后面引用变量 new 吗?比如我的用法是:

button1 = Button(frame, text=("Left On Read:\n", **VARIABLE**), fg="black", bg="white", height = 5, width = 20, command=write_lor)

变量需要是上面函数中引用的变量new

def write_lor():
    with open("data.txt", 'r+') as filehandle:
        filecontents = filehandle.readlines()
        filehandle.seek(0)
        global lor
        lor = (int(filecontents[0])+1)
        filehandle.write(str(lor)+ "\n")