Python Cant exit a Pygame game [duplicate] - python

I just spent a fair amount of time finding a 64-bit installation of pygame to use with python 3.3, (here) and now am trying to make a window. However, although the window opens up fine it does not close when it hit the x button. In fact, I have to close IDLE to close the window. I am running a 64 bit version of Win 7. Here is my code:
import pygame
import time
(width, height) = (300, 200)
screen = pygame.display.set_mode((width, height))
pygame.display.flip()
pygame.display.set_caption("Hello World")
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
When I append
time.sleep(5)
pygame.quit()
It still doesn't close. My only guess would be that pygame.quit might go inside one of the loops, but even if that were resolved I would greatly prefer being able to close the window when I want to.

Most pygame tutorials seem to suggest exiting by calling pygame.quit() and then sys.exit(). I have personally run into problems (was on a unix system though) where this still did not close the window properly. The solution was to add pygame.display.quit() specifically before pygame.quit(). That should not be necessary as far as I can tell, and I'm afraid I don't know why that solved the issue but it did.

if you want to make pygame close when window button x is pressed, put the code like this:
from sys import exit
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit()
We put exit() after pygame.quit(), because pygame.quit() makes the system exit and exit() closes that window.

Not sure but try this Because you code runs fine on my system after I add pygame.quit() at the end
import pygame
import time
(width, height) = (300, 200)
screen = pygame.display.set_mode((width, height))
pygame.display.flip()
pygame.display.set_caption("Hello World")
running = True
try:
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
pygame.quit()
except SystemExit:
pygame.quit()
Its perhaps because as Idle is made on Tkinter and thus Tkinter and Pygame main loop do not have a mutual understanding.
Your code will run very well on command prompt though.

This was the final code that worked for me on OSX whilst keeping the kernel alive on Jupyter. EDIT - it does still crash the kernel sometimes :-(
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
pygame.display.quit()
pygame.quit()
exit()
Also needed to downgrade ipython to get rid of some magic alias warning messages using:
conda install ipython=7.2.0
apparently that issue is due to be fixed in ipython 7.6.0

Suffered the same issues on Python 3.7.4 while running it from in IDE (Spyder 3.3.6). In my case the pygame.quit() would not completely close the program.
Nonetheless, adding quit() or exit() did the trick for me!

Add this at the top:
import sys
Add this where you need to quit:
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()

try using the following command:
sys.exit(0)
notice: You will need to import the sys library in order to use it.

The IDE interferes with how pygame runs the code. Try to run it from the commandline or the terminal. The problem should disappear.

To answer the original question: You must call pygame.quit() after breaking the main loop. One elegant solution goes as follows:
def run():
pygame.init()
while True:
# ...
for event in pygame.event.get():
# Handle other events
if event.type == pygame.QUIT:
return pygame.quit()

Related

PyGame window stopped showing up

I've been learning python and decided to play around with PyGame. The PyGame window randomly stops showing up when I run the script. I don't get any errors or anything, the PyGame window just won't appear.
The scripts used to work, now they don't. I had this issue before and restarted my computer a few times and eventually it started working again. But it's happening again.
So, I've got no clue what's causing it and no clue how to fix it. I've tried it with two different PyGame scripts, neither work. I'll post a sample script below.
Im using:
PyGame v2.0.1
SDL v2.0.14
Python 3.7.3
OS: Windows 10
IDE: PyCharm
I know PyGame version 2 is new, is this a bug with the new version? Thanks for your help.
Edit: restarting the computer once again fixed the issue in the short-term. I'm still looking for a long-term solution to the problem so I don't have to the restart the computer every time this happens.
Here's some sample code:
import pygame, sys
pygame.init()
windowSize = sizeW, sizeH = 1920, 1080
window = pygame.display.set_mode(windowSize)
pygame.display.set_caption('Test')
black = 0, 0, 0
speed = 0.2
x, y = 50, 50
h, w = 50, 50
blue = 0, 0, 255
guy = pygame.image.load('tile032.png')
run = True
while run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT] and x - speed > 0:
x -= speed
if keys[pygame.K_RIGHT] and x + w + speed < sizeW:
x += speed
if keys[pygame.K_UP] and y - speed > 0:
y -= speed
if keys[pygame.K_DOWN] and y + speed + h < sizeH:
y += speed
window.fill(black)
window.blit(guy, (x,y))
pygame.display.update()
Handle the closing window properly , use pygame.quit().
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
This issue usually comes when you are exiting pygame window just after calling it. It can be resolved by exiting the pygame only after the run variable goes as False. Either make the logic when your program ends or after the run function is defined as false.
After the Pygame window closes, look at the terminal to see if there is an error. If you don't use Linux, look at the place where the error usually comes up.
How I usually do it is have pygame.quit() at the very end of the code, outside of every loop, class, and method. I don't usually use sys.exit() since I am a very new pygame user, but you should also set run to false in the event loop so then it hits that pygame.quit() method at the end. And like others suggest, maybe have sys.exit() after that too.
Instead of using sys.exit(), use pygame.QUIT().I think that should do it.
I think you have to be using either pygame.quit() or just quit() or say run is False than using sys.exit() because for me personally it just broke my code while running it with pygame. So try out this for killing your pygame window:
for event in pygame.event.get():
if event.type == pygame.QUIT:
# loop will run for last time then the game will stop
run = False
Hope this helps you!

Pygame : The game stops temporarily when I am moving the window

I'm a new in PyGame and I was making a game. Until I discovered that when you were moving the window to another place of your desktop for example, the game temporarily stops. But ticks of the game still running when I used pygame.time.get_ticks().
So I made a completely new program with only the necessary code and it does the same thing.
Can someone explain me why it does it and if we can resolve this problem?
import pygame
screen = pygame.display.set_mode((800,600))
pygame.display.set_caption('The Test Program')
running = True
update_counter = 1
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
pygame.display.flip()
print(str(update_counter) + " updates")
update_counter += 1
pygame.quit()
quit()
# So try to move the window across your screen and you will see that, prints will stop and they will resume when you will release the click
So someone tell me that was normal, so I think it's only on Windows but there are no solutions. I put a script that show a pause symbol on screen when the cursor leave the window to make it normal.

pygame.quit(), quit(), or run = False?

Lets says I just have a normal game loop using pygame.
run = True
while run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
pygame.quit()
Where run = False is, should I use run = False and pygame.quit() at the end? Should I just put pygame.quit() where run = False is? Should I use quit() without pygame in front of it at all? Thanks.
I recommend to do it exactly as you do it in the question.
pygame.quit() uninitialize all pygame modules. Any further call to a pygame module (except pygame.init()) will cause an exception. To terminate a pygame application correctly, pygame.quit() has to be the called at the end. If you do pygame.quit() in the main application loop, then the application will crash if you do something after it (e.g. pygame.disaply.update()).

pygame window keeps not responding

After a long time trying to install pygame for 2.7 it finally installs and I now have it downloaded, but there is now the problem that it keeps not responding after a couple seconds of being open. Any answer will be appreciated, the code that I have so far is just.
import pygame
pygame.init()
pygame.display.set_mode((640,480))
so I need some help please.
So what you want to do, like what skrx said, is a while loop to continuously keep the code inside the while loop and the pygame window running, and as well as a for event loop, in order to be able to shut down the window. Here's how you can do it:
import pygame
pygame.init()
pygame.display.set_mode((640, 480)) # opens the display
while True: # the while loop that will keep your display up and running!
for event in pygame.event.get(): # the for event loop, keeping track of events,
if event.type == pygame.QUIT: # and in this case, it will be keeping track of pygame.QUIT, which is the X or the top right
pygame.quit() # stops pygame
There are other ways of stopping the while loop, and you could do this:
running = True
while running: # the while loop that will keep your display up and running!
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
pygame.quit()
Hope this helps!

PyCharm can't find reference in PyGame __init__.py?

OK, I’m very new to coding, and I am just learning Python. I figured I would start with some basic Pygame exercises to try to have something to program.
I’ve installed Python 3.4.3 and PyCharm. I also installed the Pygame executable “pygame-1.9.2a0-hg_5974ff8dae3c+.win32-py3.4.msi” from here: https://bitbucket.org/pygame/pygame/downloads
I ran the Pygame installer, and it seemed to complete without visible issues, though there were no obvious signs like new shortcuts on my desktop.
I then went here to try some basic test code involving Pygame:
http://pythonprogramming.net/pygame-python-3-part-1-intro/
So I copied the code from that example into my Pycharm, and ran it. It seems to create a blank Pycharm windows alright, but the PyCharm Code Inspector is giving me several warnings, and I really want to know why I am getting these warnings.
The first Pycharm warning is from line 5, “Cannot find reference ‘init’ in ‘__init__.py’
The next warning is line 16, “Cannot find reference ‘QUIT’ in ‘__init__.py’
The third and final warning is line 24, “Cannot find reference ‘quit’ in ‘__init__.py’
Why can’t it find these references? What’s wrong?
The code itself I paste below:
#! /usr/bin/python
import pygame
pygame.init()
gameDisplay = pygame.display.set_mode((800, 600))
pygame.display.set_caption('A bit Racey')
clock = pygame.time.Clock()
crashed = False
while not crashed:
for event in pygame.event.get():
if event.type == pygame.QUIT:
crashed = True
print(event)
pygame.display.update()
clock.tick(60)
pygame.quit()
quit()
This will work for you with no errors... import the system and do a system exit instead
#! /usr/bin/python
import pygame
import sys
pygame.init()
gameDisplay = pygame.display.set_mode((800, 600))
pygame.display.set_caption('A bit Racey')
clock = pygame.time.Clock()
crashed = False
while not crashed:
for event in pygame.event.get():
if event.type == pygame.QUIT:
crashed = True
print(event)
pygame.display.update()
clock.tick(60)
pygame.quit()
sys.exit()

Categories

Resources