pygam中的sys.exit()问题

2024-06-07 21:18:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在学习使用Pygame,当我使用sys.exit()时,我遇到了一个问题。代码如下:

import pygame, sys,os
from pygame.locals import * 

pygame.init() 

window = pygame.display.set_mode((468, 60)) 
pygame.display.set_caption('Game') 
screen = pygame.display.get_surface() 

file_name = os.path.join("data","image.bmp")

surface = pygame.image.load(file_name)

screen.blit(surface, (0,0)) 
pygame.display.flip() 

def input(events): 
   for event in events: 
      if event.type == QUIT: 
         sys.exit(0) 
      else: 
         print event 

while True: 
   input(pygame.event.get()) 

这只是pygame教程中的代码。当我实际尝试退出时,无论我尝试使用什么事件来sys.exit(),都会出现问题。

Traceback (most recent call last):
  File "C:/Python27/Lib/site-packages/pygame/examples/test.py", line 25, in <module>
    input(pygame.event.get())
  File "C:/Python27/Lib/site-packages/pygame/examples/test.py", line 20, in input
    sys.exit(0)
SystemExit: 0

。。。然后程序就不会退出。我在这里做错什么了?因为我注意到这段代码是为一个过时的Python版本编写的。


Tags: 代码inimporteventinputgetosdisplay
3条回答
sys.exit() 

独自一人和皮加梅在一起有点不神圣。。退出pygame应用程序的正确方法是,首先脱离主循环,然后退出pygame,然后退出程序。即

while running == True:
    # catch events
    if event_type == quit:
        running = False  # breaks out of the loop

pygame.quit()  # quits pygame
sys.exit()

而且,在我看来,你似乎没有很好地抓住这次事件。。应该是

if event.type == pygame.QUIT:

您可以在pygamehere中阅读有关事件的更多信息。

sys.exit只是抛出一个异常(SystemExit异常)。这有两个不寻常的影响:

  1. 它只在多线程应用程序中退出当前线程
  2. 异常可能已被捕获。

我解决了这个问题,正确的代码如下:

running = True
while running == True:
    for event in pygame.event.get():
        if event.type == QUIT:
            running = False  # Exiting the while loop

    screen.blit(background, (0,0))
    pygame.display.update()

pygame.quit() # Call the quit() method outside the while loop to end the application.

相关问题 更多 >

    热门问题