简体   繁体   中英

Why does my pygame window instantly close?

When I run this code:

import pygame
import time
pygame.init()


WIDTH, HEIGHT = 900, 500  # this declares the size of the window the GUI will open in
WIN = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Encryption and Decryption")  # this titles the window
FPS = 60  # this declares the  magnitude of the framerate of the window


def draw_window():
    GREY = (54, 45, 45)
    WIN.fill(GREY)  # this colours the window grey
    pygame.display.update()  # this updates the colouring of the window the next time the frame cycles


def Coursework():
    clock = pygame.time.Clock()  # this declares the refresh rate as a variable the function can use
    run = True
    while run:  # everything in this loop will only happen when the window is open
        clock.tick(FPS)  # this refreshes the frame every 1/FPS second
        for event in pygame.event.get():  # this manages events that may happen in the window
            if event.type == pygame.QUIT:
                run = False  # this ends the loop if the user quits the program
        draw_window()  # this ensures that when this function is called the window is created
    pygame.quit()


if __name__ == "__Coursework__":  # this ensures that the GUI will open when this specific program is running
    Coursework()

The pygame window closes instantly. I saw in another similar question that there are certain things an application loop must do and I believe I have done all of them, but the window still closes instantly. As I'm still a novice it's very likely that I am wrong about having hit all bases, but I do not know what I have missed.

this ensures that the GUI will open when this specific program is running

You are right, but the __name__ should be set to '__main__' in this case, so:

if __name__ == "__main__":
    Coursework()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM