I am learning to use Pygame, and when I use sys.exit()
, I run into a problem. Here is the code:
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())
It's really just the code from the pygame tutorial. The problem occurs when I actually try to exit, regardless of what event I try to use to 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
... And then the program doesn't exit. What am I doing wrong here? Because I did notice that this code was for an antiquated version of Python.
quit() function is sort of the opposite of the pygame. init() function: it runs code that deactivates the Pygame library. Your programs should always call pygame. quit() before they call sys.
QUIT with pygame. quit() . pygame. quit() is a function that closes pygame (python still running) While pygame.
You can't "clear" blits, you can only blit something else in place. You can every loop clear the whole screen, using screen. fill(), with no rect argument. Then draw blit your new scene.
Ctrl + Esc. Just pressing the ⊞ (window) key.
sys.exit()
alone is a bit unholy with pygame.. the proper way to exit a pygame app is to first break out of the mainloop then quit pygame then quit the program. ie.
while running == True:
# catch events
if event_type == quit:
running = False # breaks out of the loop
pygame.quit() # quits pygame
sys.exit()
also it seems to me that you aren't catching the event properly.. it should be
if event.type == pygame.QUIT:
you can read more about events in pygame here.
sys.exit
just throws an exception (a SystemExit exception). This has two unusual effects:
I solved this problem and the right code is below:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With