为什么我的程序假设事件绑定是一个字符串?
Why is my programming assuming an event binding is a string?
Here is the entirety of my code (100 lines)
具体来说,这是报错的部分:
def mouse_movement(self, angle, event= "<Motion>"):
x, y = event.x, event.y
relx, rely = x - self.player_coord_x, self.player_coord_y
self.angle = (180 / math.pi) * -math.atan2(rely, relx)
p = Image.open("tank.png")
p.rotate(angle)
p2 = ImageTk.PhotoImage(p)
p2.image = p2
player2 = c.create_image(self.coords[0], self.coords[1], image=p2)
在这部分代码中,我传递了一个名为 event
的参数。它将鼠标绑定到玩家的移动。但是,它给我一个属性错误:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\offcampus\AppData\Local\Programs\Python\Python38-32\lib\tkinter\__init__.py", line 1883, in __call__
return self.func(*args)
File "C:\Users\offcampus\Desktop\GameFolder\main.py", line 131, in <lambda>
c.bind_all("<Motion>", lambda x2: player.mouse_movement(180))
File "C:\Users\offcampus\Desktop\GameFolder\main.py", line 50, in mouse_movement
x, y = event.x, event.y
AttributeError: 'str' object has no attribute 'x'
程序将事件参数作为字符串,而不是作为鼠标绑定。在这种情况下我做错了什么?
您忘记传递事件,因此它使用您定义为字符串 "<Motion>"
的默认事件。要修复它,请传入事件对象(您已将其命名为 x2
):
c.bind_all("<Motion>", lambda x2: player.mouse_movement(180, x2))
Here is the entirety of my code (100 lines)
具体来说,这是报错的部分:
def mouse_movement(self, angle, event= "<Motion>"):
x, y = event.x, event.y
relx, rely = x - self.player_coord_x, self.player_coord_y
self.angle = (180 / math.pi) * -math.atan2(rely, relx)
p = Image.open("tank.png")
p.rotate(angle)
p2 = ImageTk.PhotoImage(p)
p2.image = p2
player2 = c.create_image(self.coords[0], self.coords[1], image=p2)
在这部分代码中,我传递了一个名为 event
的参数。它将鼠标绑定到玩家的移动。但是,它给我一个属性错误:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\offcampus\AppData\Local\Programs\Python\Python38-32\lib\tkinter\__init__.py", line 1883, in __call__
return self.func(*args)
File "C:\Users\offcampus\Desktop\GameFolder\main.py", line 131, in <lambda>
c.bind_all("<Motion>", lambda x2: player.mouse_movement(180))
File "C:\Users\offcampus\Desktop\GameFolder\main.py", line 50, in mouse_movement
x, y = event.x, event.y
AttributeError: 'str' object has no attribute 'x'
程序将事件参数作为字符串,而不是作为鼠标绑定。在这种情况下我做错了什么?
您忘记传递事件,因此它使用您定义为字符串 "<Motion>"
的默认事件。要修复它,请传入事件对象(您已将其命名为 x2
):
c.bind_all("<Motion>", lambda x2: player.mouse_movement(180, x2))