全局名称v未定义(但实际上是)? Tkinter的/蟒蛇

时间:2013-07-11 18:10:13

标签: python user-interface tkinter tk

我一直收到此错误“未定义全局名称v”。我知道这很可能已被大量记录,但是其他线程都没有与我的GUI情况相关。无论如何,我们走了:

v_amount= 5000

def set_v_to_something_else():
    global v
    v_amount=v_amount-1000
    v.set(v_amount)

v = StringVar()
v.set(str(v_amount))

#create button that will allow v label to be set to something else

vbutton = Button(root, text = "change v", command = set_v_to_something_else).pack()
vlabel = Label(root, textvariable=v).pack()

再一次,它表示v未定义,即使我将其设置为等于StringVar()

提前致谢

2 个答案:

答案 0 :(得分:1)

也许你收到了错误

global name v_amount is not defined

那将是因为,在此代码中,

v_amount= 5000

def set_v_to_something_else():
    global v
    v_amount=v_amount-1000
    v.set(v_amount)

当Python解析函数set_v_to_something_else时,它会将v_amount标记为局部变量,因为它出现在作业的左侧:

v_amount=v_amount-1000

稍后,当调用该函数时,由于Python将v_amount视为局部变量,因此它首先尝试评估赋值语句的右侧,并且未定义v_amount。 (请记住,它在本地命名空间中查找它,而不是全局命名空间。)

修复是在函数中添加global v_amount

def set_v_to_something_else():
    global v_amount
    v_amount = v_amount-1000
    v.set(v_amount)

您也可以删除

global v

因为您没有为v分配新值。 v.set仅仅是调用v的方法。

答案 1 :(得分:0)

v_amount= 5000

# you need to define variable 'v' here, 
# before you define function that uses it

def set_v_to_something_else():
    global v
    v_amount=v_amount-1000
    v.set(v_amount)

v = StringVar()
v.set(str(v_amount))

#create button that will allow v label to be set to something else

vbutton = Button(root, text = "change v", command = set_v_to_something_else).pack()
vlabel = Label(root, textvariable=v).pack()