【问题标题】:Why does python think a variable defined as a global variable is a local variable in a function?为什么python认为定义为全局变量的变量是函数中的局部变量?
【发布时间】: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)

它说错误是因为我在定义它们之前引用了局部变量 movexmovey(在不同的情况下)。如果我将变量movexmovey 定义为全局变量,这是怎么发生的?

我也尝试不使用 global 关键字,但我得到了同样的错误。

【问题讨论】:

标签: python global-variables


【解决方案1】:

正如@jonrsharpe 所解释的,global 将在函数内部调用。

# other variables defined above
movex = 0
movey = 0
def wasd(event):
    global movex
    global movey

    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)

【讨论】:

    猜你喜欢
    • 2023-01-05
    • 1970-01-01
    • 2015-06-25
    • 2021-06-20
    • 1970-01-01
    • 2022-08-02
    • 2019-07-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多