0

My problem appeared when I tried to make my character walk by changing one variable and thus starting an animation.The problem however is that i get an AttributeError where "'Event' object has no attribute 'key'". I find it very strange as I have written this exact code before put this problem has never appeared in previous uses. I have tried rewriting the code many times, putting it outside of the event check and inside but nothing have worked.

while turnoff == False:
    
    screen.fill(white)
    
# event checks
    
for event in pygame.event.get():
        
        if event.type == pygame.QUIT:
            turnoff = True
        elif event.type == pygame.MOUSEBUTTONDOWN:

#supposed to identify which key but can't make it work            
            if event.key == pygame.K_DOWN:
                action -= 1
                frame = 0
            if event.key == pygame.K_UP:
                action -= 3
                frame = 0

The error I get is if event.key == pygame.K_DOWN: AttributeError: 'Event' object has no attribute 'key'

Zayax
  • 1
  • 1

3 Answers3

0

The MOUSEBUTTONDOWN event has no key attribute. However, the KEDOWN event has a key attribute:

for event in pygame.event.get():
    if event.type == pygame.QUIT:
        turnoff = True
        
    elif event.type == pygame.KEYDOWN:
        if event.key == pygame.K_DOWN:
            action -= 1
            frame = 0
        if event.key == pygame.K_UP:
            action -= 3
            frame = 0
Rabbid76
  • 202,892
  • 27
  • 131
  • 174
0

The error is that you are asking for the event.key when the event is a pygame.MOUSEBUTTONDOWN. You only want to check for a keypress when there is a pygame.KEYDOWN. Your code should look like this:

for event in pygame.event.get():
        
        if event.type == pygame.QUIT:
            turnoff = True
        elif event.type == pygame.KEYDOWN:           
            if event.key == pygame.K_DOWN:
                action -= 1
                frame = 0
            if event.key == pygame.K_UP:
                action -= 3
                frame = 0
Cameron
  • 389
  • 1
  • 9
0

There is no such key attribute for MOUSEBUTTONDOWN:

Read-only. The event type specific attributes of an event. The dict attribute is a synonym for backward compatibility.

For example, the attributes of a KEYDOWN event would be unicode, key, and mod (source)

However, according to the event.c's source there might be a button member. That is, if you want to check the mouse button. Otherwise check for event.type == pygame.KEYDOWN.

Peter Badida
  • 11,310
  • 10
  • 44
  • 90