全局文件变量在函数外部不可访问(Python)

2024-04-20 03:28:08 发布

您现在位置:Python中文网/ 问答频道 /正文

当按下按钮时,变量日志打开带有时间戳的文件,当按钮关闭时,应关闭该文件。 但是,我无法关闭在另一个函数中打开的文件,即使该文件已声明为全局文件。我试着把“全局文件”放在这两个函数之外,但没用。在

 if button_status==True: #Press start
    if First_run==True: #Start a new logfile
        global log
        log=open(Fname,'a')
        log.writelines(header)
        First_run=False

     #Other code here

if button_status==False:#press stop
    log.close()
    First_run=True

enter image description here


Tags: 文件函数runlogfalsetrue声明if
2条回答

当引用函数外部的变量时,需要使用global。在

log = False
if button_status==True: #Press start
if First_run==True: #Start a new logfile
    global log
    log=open(Fname,'a')
    log.writelines(header)
    First_run=False

 #Other code here

if button_status==False:#press stop
    global log
    log.close()
    First_run=True

尝试将类似log = True的内容放在文件顶部附近,以便在任何方法或类之外声明它。然后去掉global log行,它应该可以在任何地方访问。在

相关问题 更多 >