尝试允许用户按箭头键移动图像时,如何修复 'int' 对象没有属性 'move' 错误?

How do I fix the 'int' object has no attribute 'move' error when trying to allow the user to press the arrow keys to move an image?

在我的程序中有一个部分,用户需要通过按箭头键或 'wasd' 键来移动与其角色相似的图像。我已经尝试了很多方法来修复我的代码,但它仍然会产生 AttributeError:'int' object has no attribute 'move'。 这是我的代码的一部分:

#functions to move the player image
def left(event):
    level1.move(playerImage, -10, 0)
    
def right(event):
    level1.move(playerImage, 10, 0)
    
def up(event):
    level1.move(playerImage, 0, -10)

def down(event):
    level1.move(playerImage, 0, 10)
    
    
#function to open the level 1 page
def level1():
    
    #close levelSelection page and open level1 page
    root3.destroy()
    root4 = Tk()
    
    root4.bind("<a>", left)
    root4.bind("<d>", right)
    root4.bind("<w>", up)
    root4.bind("<s>", down)
    root4.bind('<Left>', left)
    root4.bind('<Right>', right)
    root4.bind('<Up>', up)
    root4.bind('<Down>', down)
    
    #create a canvas for the level1 and put it into the root
    level1 = Canvas(root4, height = 1500, width = 2000, bg = 'LightBlue3')
    level1.pack()
    
    #bring player image onto canvas
    player = PhotoImage(file = 'Player.png')
    playerImage = level1.create_image(425, 1200, image = player)
    
    mainloop()#end level1 page

您不会通过对对象 ID 调用 move 来移动 canvas 对象,您可以通过对 canvas 调用 move 并传入对象来实现id.

level1.move(playerImage, 10, 0)

虽然在你的情况下它也不起作用,因为 level1 是一个函数也是一个局部变量,并且 playerImage 也是一个局部变量。您需要将您移动的对象的标识符保存在全局变量中(或使用 类,或 canvas 标记),并且您不应该为函数和变量使用相同的名称.

例如:

def left(event):
    level1_canvas.move(playerImage_id, -10, 0)

def level1():
    global level1_canvas, player1_id
    ...
    level1_canvas = Canvas(root4, height = 1500, width = 2000, bg = 'LightBlue3')
    ...
    player1_id = level1_canvas.create_image(...)

不过,如果您要创建多个级别 and/or 多个玩家,那么使用 类 而不是全局变量会更好。无论如何,问题的根源在于您没有正确使用 move 方法。