【问题标题】:Reference a variable that is inside a "with open" block inside a function引用函数内“with open”块内的变量
【发布时间】:2021-09-09 14:32:41
【问题描述】:
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

【问题讨论】:

  • 您必须将其设为全局变量;在write_lor 返回后,无法访问局部变量new
  • 您可以从函数内部更新按钮内的文本。

标签: python function txt


【解决方案1】:
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")

【讨论】:

  • 请添加说明此解决方案为何有效、它的目标是什么以及它试图解决的问题的文档。
  • 请详细说明,提供explanation作为您的答案。
猜你喜欢
  • 2019-12-12
  • 2018-06-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多