Exiting only Pygame window - python

Im running a Pygame window using a GUI. When for example, a user clicks on a button on the GUI, the Pygame window appears. However, when I want to quit the Pygame window, my GUI quits too. Im sure this is beacuse of the following lines of code:
for event in pygame.event.get():
if event.type==pygame.QUIT:
pygame.quit()
sys.exit()
sys.exit() exits everything, which is why the IDE closes with the Pygame window. But how do I only close the Pygae Window? Ive tried this:
for event in pygame.event.get():
if event.type==pygame.QUIT:
pygame.quit()
break
But this doesnt work. Any suggestions?
The GUI im using Pyqt4 with Python 3.

I guess that your code snippet
for event in pygame.event.get():
if event.type==pygame.QUIT:
pygame.quit()
break
is part of your main loop, running in an while loop, like
while True:
for event in pygame.event.get():
if event.type==pygame.QUIT:
pygame.quit()
break
The problem is that break will exit the for loop, not the while loop, eventually leading to an exception since you exit pygame but are probably trying to draw an the screen etc. etc.
A simple fix is to use a variable as condition for your while loop, like
quit = False
while not quit:
for event in pygame.event.get():
if event.type==pygame.QUIT:
quit = True
...
or make sure to exit the while loop
while True:
if pygame.event.get(pygame.QUIT): # only check for QUIT event
break
for event in pygame.event.get():
...

Related

Matching pygame events

The following works:
while True:
for event in pygame.event.get():
match (event.type):
case pygame.QUIT:
pygame.quit()
but if I write without "pygame." in the case expression
while True:
for event in pygame.event.get():
match (event.type):
case QUIT:
pygame.quit()
the case catches all the events and not only the QUIT one. Other potential cases are also marked unreachable by python.
Why is that? print(pygame.QUIT) and print(QUIT) both display "256".
You cant use the QUIT keyword if you only had imported pygame, to use only QUIT you need to also import pygame locals:
import pygame # Default
from pygame.locals import * # Optional
Then you can use either pygame.QUIT or QUIT.
Also instead of matching these events you can use:
for event in pygame.event.get(): # Handle events
if event.type == pygame.QUIT: # Check if the X button is clicked
pygame.quit() # Quit pygame
Then you just only need to import pygame

How to display text in pygame

I am trying to display text in pygame. I have managed to display it fine in the main loop, but then in the die() function, it doesn't appear.
def die():
while True:
deadText = text.render("You Died",1,red)
gameDisplay.blit(deadText,(500,100))
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
All functions draw in buffer and you have to send buffer to VideoCard which will display to screen.
You need pygame.display.flip() or pygame.display.update() for this.

Python video system not intilated

Here it is, I dont know what is wrong, I looked at other answers but I still dont know what is wrong?
import pygame
pygame.init()
gameWindow = pygame.display.set_mode((1000,600));
pygame.display.set_caption("Practice")
#game starts
gameActive = True
while gameActive:
for event in pygame.event.get():
#print event
if event.type == pygame.QUIT:
gameActive = False
pygame.quit()
quit()
You have pygame.quit() in your main loop, so after one iteration through the loop you are calling pygame.quit(), which causes pygame to no longer be initialized which creates the error of not having a display surface.
Moving pygame.quit() out of the main while loop fixes the issue.

Why is this tiny pygame program freezing and doing nothing?

This program infinite loops. Does nothing. Won't take input or print anything. Ideas?
import pygame
pygame.init()
running = 1
while(running):
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
print "hi"
running = 0
The problem with your script is solely that there's no window that could capture the events.
You have to create and initialize a window with pygame.display.set_mode first.
import pygame
pygame.init()
# create a window that will capture the events
pygame.display.set_mode((200, 200))
running = 1
while(running):
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
print "hi"
running = 0
Try the following:
import pygame, sys
pygame.init()
pygame.mixer.init(22050, -16, 2, 3072)
pygame.mixer.music.load("Kundara_Lake-of-Dust-320.mp3")
pygame.mixer.music.play(1, 0.0)
running = 1
while(running):
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
pygame.mixer.music.stop()
pygame.quit()
running = 0
From http://www.pygame.org/docs/ref/pygame.html
pygame.quit
Uninitialize all pygame modules that have previously been initialized. When the Python interpreter shuts down, this method is called regardless, so your program should not need it, except when it wants to terminate its pygame resources and continue. It is safe to call this function more than once: repeated calls have no effect.
Note, that pygame.quit will not exit your program. Consider letting your program end in the same way a normal python program will end.
You are looping infinitely calling pygame.quit() due to while(1).
You need to update the screen. Try it with
screen = pygame.display.set_mode((640,360),0,32)
and in the loop, write
pygame.dispay.flip()
to close the window completely, you can use
sys.exit()
just be sure to include sys in your imports
pygame does not recognize the term 'input' or 'print'. It would be a lot simpler if it did!! Instead, to get text onto the screen, you must use 'drawText('message',font,surface,(xpos,ypos) putting your own text in 'message', your own surface name in 'surface' and the x and y co-ordinates in 'xpos' and 'ypos'.

Issue with sys.exit() in pygame

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.
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:
It only exits the current thread in a multithreaded application
The exception could have been caught.
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.
I have read in some sources there is a conflict between the mainloop() in Tkinter which runs the Python shell and Pygame.init() which the sys.exit() command follows.
The suggestion was to run the game from the command line to get round the problem rather than load the game using run (F5) from the shell.
A good side effect of this was that in my space invaders game, which does a lot of variable updating: 35 times a second, was that the animation ran correctly whereas from the shell it ran poorly and was jerky.
If i use the following code:
if event.type == QUIT:
pygame.quit()
sys.exit()
the game exits correctly but leaves an error message in the shell which has no effect on the game and is largely redundant. It is just a little ugly. This does not happen from the command line.
Summary: try running the game from the command line to avoid Tkinter problems
If you still have the issue, (after breaking the loop) try using sys.exit(0) instead of sys.exit(). Hope it'll help. It worked for me. It seems pygame expects the 'status' argument (i.e. 0 here) to be passed in explicitly.
See the below example:
isRunning = True
while isRunning:
# Catch events
if event.type == pygame.QUIT:
isRunning = False # Breaks the loop
pygame.quit()
sys.exit(0)

Categories