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!
Related
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()
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.
I was displaying some text on the window but when i executed the code, it only showed a blank black window. I had no idea what was wrong, as no exceptions occurred. It just would not work.
Well i am an absolute beginner who have just passed some Python course for a couple of weeks, so i was just playing around the pygame module, instead of having big plans like game developing.
I also tried to search for similar problems but they are all so complicated that I can not understand quite well due to the long pieces of code.
I checked and no syntax is wrong, the font file is present, and the names of the objects are in the right place i.e. they are not using the wrong methods.
i don't know what else i can try...
import pygame as pg
pg.init()
win = pg.display.set_mode((720,540))
consolas = pg.font.SysFont("Consolas.ttf", 100)
text = consolas.render("hello", False , (255,255,255))
win.blit(text , (0,0))
i expected the string "hello" will be blited on the surface with the size of 100 and color to be completely white, but the whole thing did not show up at all.
You have to call pygame.display.flip or pygame.display.update to actually update the screen with the content of the win surface.
Also, you should have a main loop that handles events by calling pygame.event.get. This ensures your window stays open. Also, if you don't process events, your window becomes unresponsive and maybe doesn't even draw anything (depending on your OS/window manager)
So add this to your code:
run = True
while run:
for e in pg.event.get():
if e.type == pg.QUIT:
run = False
pg.display.update()
You need to use pg.display.update() or pg.display.flip() after you have drawn the text i.e. after win.blit line. The difference and use of the two can be found here : Difference between pygame.display.update and pygame.display.flip
As people have already commented that you have to call pygame.display.update() or pygame.display.flip()
Here's the full code:
import pygame as pg
pg.init()
win = pg.display.set_mode((720,540))
consolas = pg.font.SysFont("Consolas.ttf", 100)
running = True
while running:
text = consolas.render("hello", False , (255,255,255))
for event in pg.event.get():
if event.type == pg.QUIT:
running = False
win.blit(text , (0,0))
pg.display.flip()
pg.quit()
Whenever I run my code the Python Window that shows up does not respond.
Is there something wrong with my code or do I have to re-install pygame and python?
I get a black pygame window and then it turns white and says not responding?
Also I am new to this so please make this as simple as possible. I tried looking everywhere for the answer but could not get it in a way that I could understand.
Please help me out. Thanks :)
1 - Import library
import pygame
from pygame.locals import *
2 - Initialize the game
pygame.init()
width, height = 640, 480
screen=pygame.display.set_mode((width, height))
3 - Load Images
player = pygame.images.load("resources/images/dude.png")
4 - keep looping through
while 1:
# 5 - clear the screen before drawing it again
screen.fill(0)
# 6 - draw the screen elements
screen.blit(player, (100,100))
# 7 - update the screen
pygame.display.flip()
# 8 - loop through the events
for event in pygame.event.get():
# check if the event is the X button
if event.type==pygame.QUIT:
# if it is quit the game
pygame.quit()
exit(0)
Don't import pygame.locals. It is actually unnecessary, since you are already importing pygame.
Also, as #furas said, it should be:
player = pygame.image.load("resources/images/dude.png")
Not:
player = pygame.images.load("resources/images/dude.png")
This will clear up some of the problems in your code.
From my personal experience,if you run pygame code from IDLE it often does not respond at all.Try saving your project as a .py file and then run it with python.exe.It always works for me.
And as furas said use
player = pygame.image.load("resources/images/dude.png")
instead of
player = pygame.images.load("resources/images/dude.png")
Replace that for loop with this
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
So, I wrote this code, and it really should work. The main problem is that the code just stops responding when it opens a window and runs.
bif = "back.jpeg"
mif = "image2.png"
import pygame, sys
from pygame.locals import *
pygame.init()
screen = pygame.display.set_mode((640,360),0,32)
background = pygame.image.load(bif).convert()
mouse_c = pygame.image.load(mif).convert_alpha()
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit
sys.exit()
screen.blit(background,(0,0))
x,y = pygame.mouse.get_pos()
x -= mouse_c.get_width()/2
y -= mouse_c.get_height()/2
screen.blit(mouse_c, (x,y))
pygame.display.update()
Also, I am getting this error in IDLE.
Traceback (most recent call last):
File "C:\Users\Liam\Documents\game\Game", line 10, in <module>
background = pygame.image.load(bif).convert()
error: Couldn't open back.jpeg
When you're running your code, you have to make sure it runs in the right working directory. That would be why it doesn't find the image.
Since you're running your code in IDLE, the terminal will probably keep the process alive, so that the window won't close after the error (it would if the program terminated). Since it doesn't run event.get regularly, windows will notice that it isn't responding and that's what you're getting.
To find out what directory your script is running from, print the output of os.getcwd().
If you don't want to fiddle with paths yet and just have it run, why not set an absolute path for the image for now, like "C:\Users\My Name\Projects\Python\back.jpeg".
pygame.quit
sys.exit
should be
pygame.quit()
sys.exit()
and
screen.blit(mouse_c(x,y))
should be
screen.blit(mouse_c, (x,y))
also you may want to look into limiting it to a certain max frames a second (tutorial covers this)