Event.key does not work

Asked

Viewed 102 times

0

So I’m trying to make the screen stay fullscreen in the pygame, only event.key doesn’t work.

Follow the error:

Traceback (most recent call last):
File "C:/Users/Ailtinho/Desktop/Scirpts-Python/Jogo em python/Jogo.py", line 29, in 
    if event.key == pygame.K_f:
AttributeError: 'Event' object has no attribute 'key'.

Could someone help me?

Follow the whole code:

import pygame

clock = pygame.time.Clock()

from pygame.locals import *

pygame.init()

window = pygame.display.set_mode((800, 600))
pygame.display.set_caption('Joguinho')
altura, largura = 90, 60
move_right = False
move_left = False
dino_pos = [100, 75]
comands = pygame.key.get_pressed()

while True:
    window.fill((211, 211, 211))

    if move_right:
        dino_pos[0] += 4
    if move_left:
        dino_pos[0] -= 4

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

        if event.type  == pygame.K_f:
            window = pygame.display.set_mode((800, 600), pygame.FULLSCREEN)
        if event.key == pygame.K_ESCAPE:
            window = pygame.display.set_mode((800, 600))
        if event.type == KEYDOWN:
            if event.key == K_RIGHT:
                move_right = True
            if event.key == K_LEFT:
                move_left = True
        if event.type == KEYUP:
            if event.key == K_RIGHT:
                move_right = False
            if event.key == K_LEFT:
                move_left = False

    pygame.display.update()
    clock.tick(60)

pygame.quit()

1 answer

0

The event.key only available when events are of the "keyboard" type, when the event.type is equal to KEYDOWN or KEYUP for example

Are you trying to run it at any time at any kind of event and the pygame.event.get() takes several events, not only from the keyboard, so your script tried to access . key in an event that is not of the same type, causing the error, change to:

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

    if event.type  == pygame.K_f:
        window = pygame.display.set_mode((800, 600), pygame.FULLSCREEN)
    if event.type == KEYDOWN:
        if event.key == pygame.K_ESCAPE:
            window = pygame.display.set_mode((800, 600))
        else:
            if event.key == K_RIGHT:
                move_right = True
            if event.key == K_LEFT:
                move_left = True
    if event.type == KEYUP:
        if event.key == K_RIGHT:
            move_right = False
        if event.key == K_LEFT:
            move_left = False

Browser other questions tagged

You are not signed in. Login or sign up in order to post.