Search code examples
pythontkinterattributeerror

Why is my programming assuming an event binding is a string?


Here is the entirety of my code (100 lines)

Specifically, this is the part giving an error:

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)

In this part of the code, I am passing a parameter called event. It binds the mouse to the player's movement. However, it is giving me an Attribute Error:

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'

The program is taking the event parameter as a string, instead of taking it as a mouse binding. What am I doing wrong in this case?


Solution

  • You forgot to pass the event in, therefore it's using the default event which you defined as the string "<Motion>". To fix it, pass in the event object (which you have named x2):

    c.bind_all("<Motion>", lambda x2: player.mouse_movement(180, x2))