python namererror变量已设置为glob

2024-10-02 08:29:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我想通过单击按钮来更改微调框和输入字段的位置。 单击按钮会触发此错误:

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,那么如何修复此错误?我现在不知道该怎么办。 万事如意


Tags: toinfromifsiteplaceglobaldialog
1条回答
网友
1楼 · 发布于 2024-10-02 08:29:53

这有点胡乱猜测,因为您没有向我们展示所有代码,但是当“global”变量不是真正的全局变量,而是在一个封闭函数中定义时,我可以重现这个问题。你知道吗

最小示例:

# 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成为类的成员(如果有的话),或者甚至是外部方法的成员(比如name_of_outer_method.site),或者使它真正成为全局的,或者使用可修改的包装器类型。你知道吗

相关问题 更多 >

    热门问题