0

我不断收到此错误“未定义全局名称 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()

提前致谢

4

2 回答 2

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 解析 function 时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

于 2013-07-11T18:18:50.480 回答
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()
于 2013-07-11T18:37:43.900 回答