Reputation: 978
Making my first post here (or frankly any forum), but I was wondering why I can't exit on when the window's exit button [x] has been pressed. I have tried:
#print "Exit value ", pygame.QUIT
for et in pygame.event.get():
#print "Event type ", et.type
if et.type == pygame.KEYDOWN:
if (et.key == pygame.K_ESCAPE) or (et.type == pygame.QUIT):
print "In Here"
return True;
pygame.event.pump()# not quite sure why we do this
return False;
I've found out pygame.QUIT prints a value of 12, as I run the program an event type prints '12' when I click the [x]. The "In here" string never print on these occasions. The program exits properly when the return is true (when I press ESC on keyboard). I've looked at a few related issues: So
I'm not running on IDLE, I'm running it on:
Eclipse Juno Service Release 1.
Python 2.7.3 with the latest version of pygame for 2.7 (as of 3/4/13).
Windows 7 & 8 and Ubuntu 12.04LTS (same result besides the no soundcard error in Ubuntu)
I have run in Windows 7 by double clicking the .py file that runs the program and still does not exit on [x]. Thanks in advance.
Upvotes: 3
Views: 12639
Reputation: 19406
In your event loop,
#print "Exit value ", pygame.QUIT
for et in pygame.event.get():
#print "Event type ", et.type
#-----------------------------------------------------------------#
if et.type == pygame.KEYDOWN:
if (et.key == pygame.K_ESCAPE) or (et.type == pygame.QUIT):
#-----------------------------------------------------------------#
print "In Here"
return True;
pygame.event.pump() # not quite sure why we do this
return False;
The Problem (between the 2 #------------#
)
Let's analyse that part:
et.type == KEYDOWN
QUIT
is in if et.type == KEYDOWN
.et.type
is KEYDOWN
, it can't be QUIT
..et.type == QUIT
,What to do?
Pull your QUIT
out of KEYDOWN
's conditional, something like:
done = False
while not done:
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
done = True
break # break out of the for loop
elif event.type == pygame.QUIT:
done = True
break # break out of the for loop
if done:
break # to break out of the while loop
# your game stuff
Note:
;
after those return statementsAlways check event.type
in different if-elif blocks, like
if event.type == pygame.QUIT:
#...
elif event.type == pygame.KEYDOWN:
#...
pygame.event.pump()
there, see HereUpvotes: 2
Reputation: 7501
Your main loop should look like this
done = False
while not done:
for event in pygame.event.get():
if event.type == KEYDOWN:
if event.key == K_ESCAPE: done = True
elif event.type == QUIT:
done = True
# draw etc...
pygame.display.update()
Then, if you toggle 'done' anywhere, it will nicely quit.
Upvotes: 2