Python - UnboundLocalError: local variable referenced before assignment`

Python - UnboundLocalError: local variable referenced before assignment`

我正在编写与 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 导致错误。 谢谢

删除:

del fImage

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


见下文Minimal, Complete, and Verifiable example:

def func():
    del variable_that_never_existed

func()

您的错误的近端原因是:

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.