0

So I'm trying to get a key to close the window and stop the program when it is pressed, in this case backspace. When I press backspace however nothing happens.

keys = pygame.key.get_pressed()
if keys[pygame.K_BACKSPACE]:
     event.type == pygame.QUIT
if event.type == pygame.QUIT:
     run = False
Paul Rooney
  • 20,879
  • 9
  • 40
  • 61

1 Answers1

1

The line

event.type == pygame.QUIT

does nothing. Its returning a boolean (true/false) which you dont capture in a variable or use in any conditional statement (e.g. if).

What you should do is set run to False when you detect the key and your loop will exit before the next iteration.

Here is an example integrated with an application that listens for events, which includes key presses.

import pygame
     
pygame.init()
pygame.display.set_caption("key quitter")
screen = pygame.display.set_mode((240,180))

running = True
     
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_BACKSPACE:
                running = False

print('ending successfully')
pygame.quit()

Note the the normal quit from the gui (top right [x] on windows) also works.

Paul Rooney
  • 20,879
  • 9
  • 40
  • 61