简体   繁体   English

Python-UnboundLocalError:分配前引用的局部变量

[英]Python - UnboundLocalError: local variable referenced before assignment`

I'm writing a Python 3.6 script that works with Tkinter and an SQLite 3 database, but I get this error: 我正在编写可与Tkinter和SQLite 3数据库一起使用的Python 3.6脚本,但出现此错误:

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

The interested code is this: 感兴趣的代码是这样的:

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...

Do you know how to solve this? 你知道如何解决吗? The error results with the if and the elif in the salvataggio() function. 该错误是由于salvataggio()函数中的if和elif导致的。 Thanks 谢谢

Remove: 去掉:

del fImage

parts, it tries to remove fImage whether or not it exists. 部分,它会尝试删除fImage是否存在。


See below Minimal, Complete, and Verifiable example : 参见下面的最小,完整和可验证示例

def func():
    del variable_that_never_existed

func()

The proximal cause of your error is: 您的错误的最接近原因是:

del fImage

which works like assignment, it causes fimage to be treated as local. 就像赋值一样,它将fimage视为本地。 Therefore, you are getting an unbound-local error, which makes sense, since you never assign to fImage in the first place in Salvataggio 因此,您会遇到一个无限制的本地错误,这是有道理的,因为您从未在fImage的首位分配给Salvataggio

Anyway, yours is a special case of the typical UnboundLocalError , because it didn't involve assignment to the variable to make it get marked as local. 无论如何,您是典型的UnboundLocalError ,因为它不涉及分配变量以使其标记为local。 A common cause being a hidden assignment : 一个常见的原因是隐藏的任务

You get a plain name error if the variable is neither global nor local. 如果变量既不是全局变量也不是局部变量,则会出现纯名称错误。

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

However, the del marks the name as local: 但是, 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

This is why your check: 这就是为什么您要检查的原因:

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

is the line where it fails. 是它失败的那一行。 I do not understand why you always are checking whether fimage is in globals() . 我不明白为什么您总是检查fimage是否在globals() Note, 'fimage' in globals() can be true while fimage is a local name... hence the unbound local . 注意,当fimage是本地名称时'fimage' in globals()可以为true,因此未绑定的local

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 UnBoundLocalError:赋值之前引用的局部变量(Python) - UnBoundLocalError: local variable referenced before assignment (Python) python - UnboundLocalError:分配前引用的局部变量 - python - UnboundLocalError: local variable referenced before assignment Python UnboundLocalError:分配前引用了局部变量 - Python UnboundLocalError: local variable referenced before assignment Python | 如果变量:| UnboundLocalError:赋值前引用的局部变量&#39;variable&#39; - Python | if variable: | UnboundLocalError: local variable 'variable' referenced before assignment UnboundLocalError:在python闭包中赋值之前引用的局部变量 - UnboundLocalError: local variable referenced before assignment in python closure Python(3.3):UnboundLocalError:分配前已引用局部变量 - Python (3.3): UnboundLocalError: local variable referenced before assignment Python 分裂问题 UnboundLocalError:分配前引用了局部变量“e” - Python Splinter issue UnboundLocalError: local variable 'e' referenced before assignment UnboundLocalError:分配前引用的局部变量“转” - python - UnboundLocalError: local variable 'turn' referenced before assignment - python 如何修复 UnboundLocalError:在 Python 中分配之前引用的局部变量“df” - How to fix UnboundLocalError: local variable 'df' referenced before assignment in Python UnboundLocalError:在 Python3 中赋值之前引用了局部变量“sumOfOdd” - UnboundLocalError: local variable 'sumOfOdd' referenced before assignment in Python3
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM