7

I get the error message below when I run my code.

Traceback (most recent call last):
  File "C:/Users/user/PycharmProjects/MyDevWork/PygamesRelated/game_1.py", line 29, in <module>
    elif event.key == pygame.K_s:
AttributeError: 'Event' object has no attribute 'key'

Here is my code:

import pygame

pygame.init()

screen = pygame.display.set_mode((720, 480))
clock = pygame.time.Clock()
FPS = 60

BLACK = (0, 0, 0)
WHITE = (255, 255, 255)

rect = pygame.Rect((0, 0), (32, 32))
image = pygame.Surface((32, 32))
image.fill(WHITE)

while True:
    clock.tick(FPS)

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            quit()

        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_w:
                rect.move_ip(0, -2)
        elif event.key == pygame.K_s:
            rect.move_ip(0, 2)
        elif event.key == pygame.K_a:
            rect.move_ip(-2, 0)
        elif event.key == pygame.K_d:
            rect.move_ip(2, 0)

screen.fill(BLACK)
screen.blit(image, rect)
pygame.display.update()

I am using python 3.7 and Pycharm.

2
  • 1
    Your indentation is wrong. The line elif event.key == pygame.K_s and the like should be at the same level as if event.key == pygame.K_w. Commented Aug 9, 2019 at 14:42
  • related question Commented Aug 9, 2019 at 15:06

1 Answer 1

9

As mentioned, your indentation is the problem here. Everything checking the event.key should be "inside" the KEYDOWN check. Change your while loop to:

while True:
    clock.tick(FPS)

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            quit()

        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_w:
                rect.move_ip(0, -2)
            elif event.key == pygame.K_s:
                rect.move_ip(0, 2)
            elif event.key == pygame.K_a:
                rect.move_ip(-2, 0)
            elif event.key == pygame.K_d:
                rect.move_ip(2, 0)
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks to both of you StardustGogeta and Akaisteph7. Wrong indentation was actually the cause of my problem. I followed your advice and the problem is solved. Once again, thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.