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

Python 如何修复';int';对象没有属性';移动';尝试允许用户按箭头键移动图像时出错?,python,tkinter,move,Python,Tkinter,Move,在我的程序中有一部分,用户需要通过按箭头键或“wasd”键来移动类似于他们角色的图像。我已经尝试了很多方法来修复我的代码,但它仍然会生成AttributeError:“int”对象没有属性“move”。 这是我代码的一部分: #functions to move the player image def left(event): level1.move(playerImage, -10, 0) def right(event): level1.move(playerIm

在我的程序中有一部分,用户需要通过按箭头键或“wasd”键来移动类似于他们角色的图像。我已经尝试了很多方法来修复我的代码,但它仍然会生成AttributeError:“int”对象没有属性“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
#移动播放器图像的功能
def left(事件):
一级移动(玩家图像,-10,0)
def权限(事件):
一级移动(玩家图像,10,0)
def up(事件):
一级移动(玩家图像,0,-10)
def关闭(事件):
一级移动(玩家图像,0,10)
#函数打开级别1页面
def level1():
#关闭levelSelection页面并打开level1页面
root3.destroy()
root4=Tk()
root4.bind(“,左)
root4.bind(“,右)
根4.绑定(“,向上)
root4.bind(“,向下)
根4.绑定(“”,左)
根4.绑定(“”,右)
根4.绑定(“”,向上)
根4.绑定(“”,向下)
#为level1创建画布并将其放入根目录中
level1=Canvas(root4,高度=1500,宽度=2000,背景='LightBlue3')
level1.pack()
#将玩家图像放到画布上
player=PhotoImage(文件='player.png')
playerImage=level1.创建_图像(4251200,图像=player)
mainloop()#结束级别1页

在对象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
方法。

对于
level1
有两种定义。其中一个是函数(
def level1()
),另一个是tkinter画布(
level1=canvas(…)
)。当你有这样的变量名冲突时,可能会发生很多问题,所以我认为你是在用变量
level1
来做其他事情,比如
level1=。创建图像(…)
哪个设置
level1
作为
int
对象