代码之家  ›  专栏  ›  技术社区  ›  maicol07

Python-UnboundLocalError:赋值前引用的局部变量`

  •  0
  • maicol07  · 技术社区  · 8 年前

    我正在编写一个与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。 谢谢

    2 回复  |  直到 8 年前
        1
  •  2
  •   Nae    8 年前

    删除:

    del fImage
    

    零件,它试图移除 fImage 是否存在。


    见下文 Minimal, Complete, and Verifiable example :

    def func():
        del variable_that_never_existed
    
    func()
    
        2
  •  1
  •   juanpa.arrivillaga    8 年前

    错误的近端原因是:

    del fImage
    

    就像任务一样 fimage 被视为当地人。因此,您将得到一个未绑定的本地错误,这是有意义的,因为您从未将 fImage 首先在 Salvataggio

    总之,你的是典型的 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公司 是本地名称。。。因此,未绑定 地方的 .