【发布时间】:2021-10-24 14:23:00
【问题描述】:
在这段代码中:
# other variables defined above
global movex
movex = 0
global movey
movey = 0
def wasd(event):
key = event.char
if key == 'w':
movey = -5
elif key == 'a':
movex = -10
#elif key == 's':
#movey = 10
elif key == 'd':
movex = 10
p.moverect(movex,movey)
tk.bind('<Key>', wasd)
tk.bind('<Key>', wasd)
largetext = Font(size=13)
p = player(sx1=950,sy1=520,sx2=975,sy2=545)
它说错误是因为我在定义它们之前引用了局部变量 movex 和 movey(在不同的情况下)。如果我将变量movex 和movey 定义为全局变量,这是怎么发生的?
我也尝试不使用 global 关键字,但我得到了同样的错误。
【问题讨论】:
-
因为你分配给它。全局关键字需要inside函数。
-
这能回答你的问题吗? referenced before assignment error in python