python NameError变量已设置为全局变量
我想通过单击按钮来更改spinbox和输入字段的位置。 单击按钮会触发此错误:python NameError变量已设置为全局变量,python,global,Python,Global,我想通过单击按钮来更改spinbox和输入字段的位置。 单击按钮会触发此错误: Exception in Tkinter callback Traceback (most recent call last): File "C:\Python27\lib\lib-tk\Tkinter.py", line 1470, in __call__ return self.func(*args) File "GUI.py", line 79, in changesite if (site==0): Name
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Python27\lib\lib-tk\Tkinter.py", line 1470, in __call__
return self.func(*args)
File "GUI.py", line 79, in changesite
if (site==0):
NameError: global name 'site' is not defined
我的代码如下:
else:
w = Spinbox(dialog, from_=5, to=getmodulo(ceiling), increment = 5.0, state='readonly',font = "bold")
e = Entry(dialog,font = "bold")
e.place(x=390,y=120)
w.place(x=20,y=120)
site = 0
def changesite():
global site
if (site==0):
e.destroy()
w.destroy()
ws = Spinbox(dialog, from_=5, to=getmodulo(ceiling), increment = 5.0, state='readonly',font = "bold")
es = Entry(dialog,font = "bold")
es.place(x=20,y=120)
ws.place(x=390,y=120)
site = 1
if (site ==1):
ws.destroy()
es.destroy()
w = Spinbox(dialog, from_=5, to=getmodulo(ceiling), increment = 5.0, state='readonly',font = "bold")
e = Entry(dialog,font = "bold")
e.place(x=390,y=120)
w.place(x=20,y=120)
site = 0
正如您所看到的,我使用global for site,那么如何修复此错误?我现在不知道该怎么办。
一切都好 这有点胡乱猜测,因为您没有向我们展示所有代码,但当全局变量不是真正的全局变量,而是在封闭函数中定义时,我可以重现问题 最简单的例子:
# global f is expected here...
def foo():
f = 42 # ... but defined here
def bar():
global f
f = f + 1 # this causes a NameError
bar()
foo()
相反,您可以使site成为类的成员(如果有的话),或者甚至是外部方法的成员(如\u outer\u method.site的名称),或者使其真正成为全局的,或者使用可修改的包装类型。您能向我们展示更多的代码吗?也就是说,这个缩进表明这个代码是什么类型的块,在什么地方调用了changesite函数。changesite是通过单击按钮从命令中调用的。我认为不需要这个代码段周围的代码。不是全部代码,我只是想看看是否在else语句或类/函数定义中声明了site。您向我们展示的代码不会导致任何错误,第2行中的IndentationError除外。您可以使用Class属性site定义一个类,它将作为静态变量工作