微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

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

在我的程序中有一个部分,用户需要通过按箭头键或“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,-10)

def down(event):
    level1.move(playerImage,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 来移动画布对象,而是通过在画布上调用 move 并传入对象 id 来移动画布对象。

level1.move(playerImage,10,0)

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

例如:

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(...)

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。