I can’t make the Pygame window close button work

Asked

Viewed 484 times

1

I’m learning to use Pygame functions, but I got caught up in this problem. I created a window with Pygame, and then I made this code so when I click the exit button the window closes.

Code

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            break
        print(event)
    # Atualizando a tela
    pygame.display.update()

pygame.quit()

I can’t understand why it doesn’t work, the program during execution shows no error, but when I click the close button, nothing happens.

3 answers

2


Try putting pygame.display.quit() before pygame.quit(), already out of the loop. I’ve seen people who only managed to make it work by putting Exit() after, but only try it if the first option doesn’t work.

2

this is easy to solve, just use the native function Exit, whose goal is to close the program

pygame.quit() is for solving a pygame bug and should always be called before closing

import pygame
from pygame.locals import *

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


1

Follows a basic code to complement the response of Henrique Seta.

In this example the while will be executed while sair is equal to False.

Note that inside the for if the event QUIT the variable is captured sair will be defined as True closing the loop to close the program as the pygame.quit().

import pygame

def main():        
    pygame.init()
    tela = pygame.display.set_mode([300,300])
    pygame.display.set_caption("Iniciando com Pygame")    
    cor = (255,255,255) # cor branca
    sair = False

    while sair != True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sair = True               

            tela.fill(cor) # preenche a tela com a cor branca    

            pygame.display.update() 

    pygame.quit()

main()

Browser other questions tagged

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