gpt4 book ai didi

python-3.x - 修改全局变量的NameError

转载 作者:行者123 更新时间:2023-12-03 16:38:10 26 4
gpt4 key购买 nike

这是尝试在单击按钮时增加数字。

def something():
CP = 0
counter = StringVar()
counter.set("0")
def click():
global CP
global counter
CP = CP + 1
counter.set(str(CP))
label5=Label(window, textvariable=counter, font=("Georgia", 16), fg="blue")
button5=Button(window, text='Make a Clip', command=click)
label5.pack()
button5.pack()

本节第 6 行有一个名称错误。

Traceback (most recent call last):
File "D:\Program Files\Python\Python36\lib\tkinter\__init__.py", line 1699, in __call__
return self.func(*args)
File "D:\Program Files\Python\Python36\Paperclips.py", line 14, in click
CP = CP + 1
NameError: name 'CP' is not defined

代码有什么问题?

最佳答案

CP 不是全局,而是非本地。只需将 global 替换为 nonlocal 即可在嵌入函数中找到变量。

counter 有细微的差别。您不需要为另一个变量 counter 执行此操作,因为您只是在使用引用(它与 += 不同)。

简单的独立示例:

def a():
x = 0
def b():
nonlocal x # tell python that x is in the function(s) above
x += 1
b()
print(x)

a()

打印1

在列表中使用 +=append 时的有趣区别:

def a():
l = []
def b():
l.append(435)
b()
print(l)

a()

现在可以了:

def a():
l = []
def b():
# nonlocal l # uncomment for it to work
l += [435]
b()
print(l)

a()

这应该是等效的,但是对于 += l 需要“声明”为 nonlocal(更多信息在这里:Concatenating two lists - difference between '+=' and extend() 和相关答案:https://stackoverflow.com/a/24261311/6451573 )

但是,对于整数,由于整数的不变性,+= 不能被函数调用替换 BTW。所以 nonlocal 仍然是唯一可行的选择。

关于python-3.x - 修改全局变量的NameError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51748291/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com