首页 > 解决方案 > 有没有办法用 MOUSEBUTTONDOWN 事件关闭 pygame 窗口?

问题描述

我正在尝试制作一个退出 pygame 的可点击图像,但我不确定如何关闭它。我曾尝试使用 pygame.quit() 和 sys.exit() 但加载了一秒钟但没有做任何事情。我将在这里展示我的代码(唯一相关的代码是 x 和 y 变量以及底部的退出按钮):

import pygame, sys

clock = pygame.time.Clock()

from pygame.locals import *
pygame.init() # inititates Pygame

pygame.display.set_caption('Lightmind')

screen = pygame.display.set_mode((0, 0), pygame.FULLSCREEN) # initiates the window

logo = pygame.image.load("GameLogo.png").convert()
logo = pygame.transform.scale(logo, (256, 256))
start_button = pygame.image.load("StartButton.png").convert()
start_button = pygame.transform.scale(start_button, (256, 256))
exit_button = pygame.image.load("ExitButton.png").convert()
exit_button = pygame.transform.scale(exit_button, (256, 100))

x_2 = 560
y_2 = 400

fade_in = True
fade_out = True
fade_in_ball = True
fade_in_start = True
fade_in_exit = True

running = True
while running: # game loop

    for event in pygame.event.get():
        if event.type == QUIT:
            running = False
            pygame.quit()
            sys.exit()
            
    # fade in the logo
    if fade_in == True:
        for i in range(255):
            screen.fill((0,0,0))
            logo.set_alpha(i)
            screen.blit(logo, (560,260))
            pygame.display.flip()
            clock.tick(60)
            fade_in = False

    # fade out the logo
    if fade_out == True:
        for i in range(255):
            screen.fill((0,0,0))
            logo.set_alpha(255-i)
            screen.blit(logo, (560,260))
            pygame.display.flip()
            clock.tick(60)
            fade_out = False


    # fade in the start button
    if fade_in_start == True:
        for i in range(255):
            start_button.set_alpha(i)
            screen.blit(start_button, (560, 240))
            pygame.display.flip()
            clock.tick(60)
            fade_in_start = False
    
    # fade in the exit button
    if fade_in_exit == True:
        for i in range(255):
            exit_button.set_alpha(i)
            screen.blit(exit_button, (x_2, y_2))
            pygame.display.flip()
            clock.tick(60)
            fade_in_exit = False
            # make exit button exit game
            if event.type == pygame.MOUSEBUTTONDOWN:
                x_2, y_2 = event.pos
                if exit_button.get_rect().collidepoint(x_2, y_2):
                    pygame.quit()
                    sys.exit()

    

    pygame.display.update()

任何帮助表示赞赏!

标签: pythonpygame

解决方案


您正在事件循环之外检查事件。将其向上移动:

    for event in pygame.event.get():
        if event.type == QUIT:
            running = False
            pygame.quit()
            sys.exit()
        elif event.type == pygame.MOUSEBUTTONDOWN:
            x_2, y_2 = event.pos
            if exit_button.get_rect().collidepoint(x_2, y_2):
                pygame.quit()

推荐阅读