首页 > 解决方案 > 如何让它在pygame中退出?

问题描述

import pygame
import os
pygame.font.init()
pygame.mixer.init()

WIDTH, HEIGHT = 900, 500
WIN = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("TIMER")
WHITE = (255, 255, 255)
black = (0, 0, 0)
MENU_bg = pygame.transform.scale(pygame.image.load(os.path.join("menu.png")), (WIDTH, HEIGHT))
SPACE = pygame.transform.scale(pygame.image.load(os.path.join("SPACE.png")), (WIDTH, HEIGHT))
START_button = pygame.transform.scale(pygame.image.load(os.path.join("START.png")), (300, 150))
STOP_button = pygame.transform.scale(pygame.image.load(os.path.join("STOP.png")), (300, 150))
RESET_button = pygame.transform.scale(pygame.image.load(os.path.join("RESET.png")), (300, 150))
re = 0
FPS = 100
FONT = pygame.font.SysFont("Comic sans", 100)
FONT2 = pygame.font.SysFont("Comic sans", 30)
quiting = 0


def test_exit():
    if quiting == 1:
        exit()
    else:
        pass

def draw_menu():
    WIN.blit(MENU_bg, (0, 0))
    pygame.display.update()

def main_menu():
    running = True
    quiting = 0
    clock = pygame.time.Clock()
    FPS = 60
    draw_menu()
    while running:
        clock.tick(FPS)
        draw_menu()
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                quiting = 1
            if event.type == pygame.MOUSEBUTTONUP:
                mouse_pos = pygame.mouse.get_pos()
                print(mouse_pos)
                if mouse_pos[0] >= 0 and mouse_pos[0] <= 450 and mouse_pos[1] >= 200 and mouse_pos[1] <= 500:
                    #I will connect to a new function here
                    running = False




if __name__ == "__main__":
    main_menu()

为什么没有正常退出?我尝试了很多次,但它不起作用。运行代码时我没有收到错误消息,但我无法退出。我已经阅读了几个教程,并没有看到我做错了什么。如何更改我的代码以使其在pygame.QUIT时退出?

标签: pythonpygame

解决方案


您从未调用过该test_exit函数。

import pygame
import sys

WIDTH, HEIGHT = 900, 500
WIN = pygame.display.set_mode((WIDTH, HEIGHT))

def test_exit(quiting):
    if quiting:
        pygame.quit()
        sys.exit()

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

请注意,exit这不会关闭 pygame 窗口。你将不得不使用pygame.quit()它。sys.exit()如果您想终止程序,请在此之后调用 。


推荐阅读