首页 > 解决方案 > 如何在pygame中退出窗口?

问题描述

我想在按下 esc 按钮后关闭游戏。我能怎么做?我应该把它放在哪里?我也发现了一些我无法解决的问题,所以如果你为我解决了我会很高兴

这是代码:

#Import Libraries
import pygame
import random

#PyGame Initialization
pygame.init()

#Images Variables
background = pygame.image.load('images/sfondo.png')
bird = pygame.image.load('images/uccello.png')
base = pygame.image.load('images/base.png')
gameover = pygame.image.load('images/gameover.png')
tube1 = pygame.image.load('images/tubo.png')
tube2 = pygame.transform.flip(tube1, False, True)

#Display Create
display = pygame.display.set_mode((288,512))
FPS = 60

#Define Functions
def draw_object():
    display.blit(background, (0,0))
    display.blit(bird, (birdx, birdy))

def display_update():
    pygame.display.update()
    pygame.time.Clock().tick(FPS)

def animations():
    global birdx, birdy, bird_vely
    birdx, birdy = 60, 150
    bird_vely = 0

#Move Control
animations()

while True:
    bird_vely += 1
    birdy += bird_vely
    for event in pygame.event.get():
        if ( event.type == pygame.KEYDOWN
             and event.key == pygame.K_UP):
            bird_vely = -10
        if event.type == pygame.QUIT:
            pygame.quit()
        draw_object()
        display_update()

标签: pythonpygame

解决方案


好吧,您可以通过在代码中实现以下代码片段来做到这一点:

running = True
while running:
    # other code
    event = pygame.event.wait ()
    if event.type == pygame.QUIT:
         running = False  # Be interpreter friendly
pygame.quit()

确保在退出主函数之前调用pygame.quit()

也可以参考这个线程 Pygame escape key to exit


推荐阅读