【问题标题】:Python - UnboundLocalError: local variable referenced before assignment`Python - UnboundLocalError:赋值前引用的局部变量`
【发布时间】:2018-06-29 22:17:39
【问题描述】:

我正在编写一个可与​​ Tkinter 和 SQLite 3 数据库配合使用的 Python 3.6 脚本,但出现此错误:

if "fImage" in globals() and not(fImage==None): UnboundLocalError: local variable 'fImage' referenced before assignment

感兴趣的代码是这样的:

from tkinter import *
from ttk import *
from tkinter import Toplevel, Tk
import sqlite3 as sql
def Salvataggio(mode,nome,cognome,sitoweb,email,idx):
    conn=sql.connect(os.path.join(path, fn_prof),isolation_level=None)
    c=conn.cursor()
    if mode=="add":
        if "fImage" in globals() and not(fImage==None):
            c.execute("INSERT INTO prof VALUES ('{}','{}','{}','{}','{}','{}')".format(len(prof.keys())+1,nome.get(),cognome.get(),fImage,sitoweb.get(),email.get()))
        else:                
            c.execute("INSERT INTO prof VALUES ('{}','{}','{}','{}','{}','{}')".format(len(prof.keys())+1,nome.get(),cognome.get(),"",sitoweb.get(),email.get()))
        del fImage
        wa.destroy()
    elif mode=="edit":
        if "fImage" in globals() and not(fImage==None):
            c.execute("""UPDATE prof
                      SET nome = '{}', cognome = '{}', imageURI='{}', web='{}', email='{}'
                      WHERE ID={}; """.format(nome.get(),cognome.get(),fImage,sitoweb.get(),email.get(),idx))
        else:                
            c.execute("""UPDATE prof
                      SET nome = '{}', cognome = '{}', web='{}', email='{}'
                      WHERE ID={}; """.format(nome.get(),cognome.get(),sitoweb.get(),email.get(),idx))
        del fImage
def selImmagine(bi):
    if not("fImage" in globals()):
        global fImage
    fImage=askopenfilename(filetypes=[(_("File Immagini"),"*.jpg *.jpeg *.png *.bmp *.gif *.psd *.tif *.tiff *.xbm *.xpm *.pgm *.ppm")])
    # other code...

你知道如何解决这个问题吗? salvataggio() 函数中的 if 和 elif 导致错误。 谢谢

【问题讨论】:

  • 为什么使用if not ("fImage" in globals())?无条件使用global fImage。此外,您发布的代码与您声称收到的错误不匹配。错误显示if 有两个条件,代码显示一个条件。

标签: python variables tkinter sqlite local


【解决方案1】:

删除:

del fImage

部分,它会尝试删除fImage,无论它是否存在。


见下文Minimal, Complete, and Verifiable example

def func():
    del variable_that_never_existed

func()

【讨论】:

    【解决方案2】:

    您的错误的近端原因是:

    del fImage
    

    其工作方式类似于赋值,它导致fimage 被视为本地。因此,您会收到一个未绑定的本地错误,这是有道理的,因为您从未在 Salvataggio 中首先分配给 fImage

    无论如何,你的情况是典型的UnboundLocalError 的一个特例,因为它不涉及分配给变量以使其被标记为本地。一个常见的原因being a hidden assignment

    如果变量既不是全局变量也不是局部变量,您会得到一个简单的名称错误。

    In [1]: def f():
       ...:     if x in {}:
       ...:         pass
       ...:
    
    In [2]: f()
    ---------------------------------------------------------------------------
    NameError                                 Traceback (most recent call last)
    <ipython-input-2-0ec059b9bfe1> in <module>()
    ----> 1 f()
    
    <ipython-input-1-80c063ba8db6> in f()
          1 def f():
    ----> 2     if x in {}:
          3         pass
          4
    
    NameError: name 'x' is not defined
    

    但是,del 将名称标记为本地:

    In [3]: def f():
       ...:     if x in {}:
       ...:         pass
       ...:     del x
       ...:
    
    In [4]: f()
    ---------------------------------------------------------------------------
    UnboundLocalError                         Traceback (most recent call last)
    <ipython-input-4-0ec059b9bfe1> in <module>()
    ----> 1 f()
    
    <ipython-input-3-5453b3a29937> in f()
          1 def f():
    ----> 2     if x in {}:
          3         pass
          4     del x
          5
    
    UnboundLocalError: local variable 'x' referenced before assignment
    

    这就是你支票的原因:

    if "fImage" in globals() and not(fImage==None):
    

    是失败的那一行。我不明白你为什么总是检查fimage 是否在globals() 中。注意,'fimage' in globals() 可以为真,而 fimage 是本地名称...因此未绑定 local

    【讨论】:

      猜你喜欢
      • 2015-06-14
      • 1970-01-01
      • 2012-11-14
      • 2013-11-29
      • 2019-09-02
      • 1970-01-01
      • 2011-10-31
      • 2020-05-05
      • 1970-01-01
      相关资源
      最近更新 更多