python - 如何让它在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时退出?
解决方案
您从未调用过该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()
如果您想终止程序,请在此之后调用 。
推荐阅读
- java - Spring Boot 慢 XHR 传输率
- node.js - 尝试安装 NodeJS 14 会改为安装 NodeJS 8
- javascript - 在带有 lit-element Web 组件的 html 渲染中插入一个节点
- node.js - 如何更改温斯顿时间戳中的时区?节点js
- c - C 编程中的长整数范围
- plotly - 使用 Plotly Express 渲染动画散点图时提高性能
- python - 在python中合并两个数据框的替代方法
- c - 为什么我会收到错误消息?
- python - 如何通过 Gitlab CI 成功安装 fbprophet?
- java - SAP Hana 中基于 JDBC 的 SQL UPDATE 不是持久的