I am not able to run anything using pygame as whenever I run anything, even a very simple program displaying a circle, the program yields a black screen which does nothing.
The black screen I am talking about is this black screen
What is this exactly? and is there a way to fix it?
Edit:
I forgot to mention that the program appears to be running well and I get no errors.
Edit #2: This is my very simple program:
import pygame
pygame.init()
screen = pygame.display.set_mode([500, 500])
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
screen.fill((255, 255, 255))
SCREEN_TITLE = 'Chess Game'
pygame.display.set_caption(SCREEN_TITLE)
pygame.draw.circle(screen, (0, 0, 255), (250, 250), 75)
pygame.display.flip()
pygame.quit()
Edit #3: a picture of what is showing on the python console
after I press the exit button
before I press the exit button
You may experience two separated issues:
Issue 1: Pygame installation on MacOS
There are some documented problems when running PyGame with MacOS. Please check that you have correctly installed and setup pygame in your machine. This post might be useful.
Issue 2: Code incorrections
Apart from that, your code has several issues. Your running loop does not display anything since it is stuck processing events and nothing more. Therefore, you see a black screen. Notice that you are printing the screen and the circle when the execution is over.
When using pygame I suggest to differentiate between:
Initialisation: Setup pygame and screen. Render any static content.
Running loop: Process events and render any dynamic content.
End: Display any end animation/object and finalise pygame.
I suggest the following modifications:
Render first the screen
In the running loop just process the events and render the circle
I have added debug messages. You can enable and disable them by running python mygame.py and python -O mygame.py. Be aware that the print statements inside the running loop will print a lot of messages.
Here is the code:
#!/usr/bin/python
# -*- coding: utf-8 -*-
# For better print formatting
from __future__ import print_function
# Imports
import pygame
#
# MAIN FUNCTION
#
def main():
# Setup display and static content
if __debug__:
print("Initialising pygame")
pygame.init()
SCREEN_TITLE = 'Chess Game'
pygame.display.set_caption(SCREEN_TITLE)
screen = pygame.display.set_mode([500, 500])
screen.fill((255, 255, 255))
pygame.display.flip()
# Running loop
running = True
while running:
if __debug__:
print("New iteration")
# Process events
if __debug__:
print("- Processing events...")
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# Display any dynamic content
if __debug__:
print("- Rendering dynamic content...")
pygame.draw.circle(screen, (0, 0, 255), (250, 250), 75)
# Update display
if __debug__:
print("- Updating display...")
pygame.display.flip()
# End
if __debug__:
print("End")
pygame.quit()
#
# ENTRY POINT
#
if __name__ == "__main__":
main()
Debug output:
$ python mygame.py
pygame 1.9.6
Hello from the pygame community. https://www.pygame.org/contribute.html
Initialising pygame
New iteration
- Processing events...
- Rendering dynamic content...
- Updating display...
.
.
.
New iteration
- Processing events...
- Rendering dynamic content...
- Updating display...
End
Display:
Related
I've read everything I could find about the mouse in pygame and yet I miss something.
The device has (and will not) have a mouse attached so I need to remove the cursor from the game surface, ideally even before it draws the first screen.
But no matter what I try I always have a big oppalin cursor in the middle of the screen.
My current function is this :
# initialize the pygame module
pygame.init()
# create a surface on screen that has the size of 240 x 180
screen = pygame.display.set_mode((160,80))
# define a variable to control the main loop
running = True
pygame.display.flip()
# main loop
while running:
screen.fill((0, 0, 0))
# hide cursor
pygame.mouse.set_pos((160,80)) # my screen is actually 160 x 80 px so this should hide it by pushing it over the edge
pygame.mouse.set_visible(False) # this should hide the mouse plain and simple
# Here I do other unrelated (but working) stuff, like displaying images and text
# event handling, gets all event from the event queue
for event in pygame.event.get():
# only do something if the event is of type QUIT
if event.type == pygame.QUIT:
# change the value to False, to exit the main loop
running = False
pygame.display.flip()
And the mouse is still on screen, sometimes after a while it disappears.
I tried other method like making the cursor transparent, but that crash the app.
Note that I'm running Pygame on an Alpine Linux with direct output to the framebuffer on a Raspberry Pi. There's no mouse attached to the device but if I connect one I can move the cursor around.
Pygame is Version 2.1.2 (compiled and installed by pip)
Python is 3.10.0
Any help or pointer would be greatly appreciated.
(sorry if it's a dumb question; I'm a total noob with python/pygame)
Just write the set_visible(False) outside the main loop, you don't need to call this every frame:
pygame.init()
screen = pygame.display.set_mode((160,80))
pygame.mouse.set_visible(False) # Hide cursor here
running = True
pygame.display.flip()
# main loop
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# unrelated with your question but I also suggest that you clear your background inside the loop, at the contrary you likely will need this at each frame
screen.fill((0, 0, 0))
# ... your code, blitting images etc
pygame.display.flip()
I'm using pygame and updating to the screen every loop of the main loop. What I don't understand is nothing will update until I add a for loop looking for events, then suddenly all the updating does occur. Why is this?
def run(self):
two_pm = get_stand_up_timestamp()
pygame.init()
font = pygame.font.Font(None, 72)
screen = pygame.display.set_mode(self._dimensions)
before_two = True
while before_two:
# Blit the time to the window.
# Update Screen.
current_time = datetime.datetime.now()
text = font.render(f'{current_time.hour} : {current_time.minute} : {current_time.second}', True, (0, 0, 0))
blit_center = (
self._dimensions[0] // 2 - (text.get_width() // 2),
self._dimensions[1] // 2 - (text.get_height() // 2)
)
screen.fill((255, 255, 255))
screen.blit(text, blit_center)
pygame.display.flip()
# Get events.
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_q:
sys.exit()
When you call pygame.event.get() (or pump()), pygame processes all events that your window manager send to the window managed by pygame.
You don't see these events as they are not returned by get(), but pygame handles them internally. These events could be WM_PAINT on Windows or Expose on Linux (IIRC pygame uses Xlib), or other events (I guess you could look them up in pygame's source code).
E.g. if you run pygame on Windows, Pygame has to call Windows' GetMessage function, otherwise:
If a top-level window stops responding to messages for more than several seconds, the system considers the window to be not responding and replaces it with a ghost window that has the same z-order, location, size, and visual attributes. This allows the user to move it, resize it, or even close the application. However, these are the only actions available because the application is actually not responding.
So the typical behaviour if you don't let pygame process the events is that it will basically run, but the mouse cursor will change to the busy cursor and you can't move the window before it will eventually freeze.
If you run pygame on other systems, e.g. Linux, you only see a black screen. I don't know the internals of the message loop when pygame runs on Linux, but it's similiar to the Windows message loop: you have to process the events in the queue to have pygame call Xlib's XNextEvent function (IIRC) to give the window manager a chance to draw the window.
See e.g. Message loop in Microsoft Windows and/or Xlib for more information on that topic.
No idea why it doesn't work on your end, however when I run
def run():
width = 500
height = 500
pygame.init()
font = pygame.font.Font(None, 72)
screen = pygame.display.set_mode((width, height))
before_two = True
while before_two:
# Blit the time to the window.
# Update Screen.
current_time = datetime.datetime.now()
text = font.render(f'{current_time.hour} : {current_time.minute} : {current_time.second}', True, (0, 0, 0))
blit_center = (
width // 2 - (text.get_width() // 2),
height // 2 - (text.get_height() // 2)
)
screen.fill((255, 255, 255))
screen.blit(text, blit_center)
pygame.display.flip()
run()
Everything works fine update wise. The clock ticks every second so it may be something with your version of python or pygame. Try updating them both. Alternately it could be a problem with how you get pass pygame the dimensions of the window with the run(self) and self._dimensions. Trying using static dimensions like I did above and see if that works on your end. Sadly without more code to see how you call run() its difficult to fully debug whats wrong.
This question already has answers here:
Why is my PyGame application not running at all?
(2 answers)
Closed 2 years ago.
I started learning pygame, wrote a simple program to display some text on the screen.
import pygame, time
pygame.init()
window = pygame.display.set_mode((600,300))
myfont = pygame.font.SysFont("Arial", 60)
label = myfont.render("Hello Pygame!", 1, (255, 255, 0))
window.blit(label, (100, 100))
pygame.display.update()
time.sleep(15)
pygame.quit()
But it keeps crashing.
I am using python2.7
The issue is that you are running the code only once and not repeating the lines of code that need to be repeated for every frame.
Then you are calling pygame.quit() without exiting the Python thread with quit() which results in the windows just "crashing" or not responding.
To fix this problem:
Include some code inside a while loop that will run on every frame and thus keep the program running and responding.
Make sure that initialization code is only ran once.
Add in some event handling to let the user exit the program when the "X" button is clicked.
Some useful additions:
Included a Clock which allows for an FPS-cap.
Filled the screen with black every frame
Exited the game properly with pygame.quit() to exit the pygame window and sys.exit() to exit the Python thread.
A Clock in pygame game allows you to specify an FPS. At the end of every main game loop iteration (frame) you call clock.tick(FPS) to wait the amount of time that will ensure the game is running at the specified framerate.
Here is the revised code example:
import pygame
import sys
# this code only needs to be ran once
pygame.init()
window = pygame.display.set_mode((600,300))
myfont = pygame.font.SysFont("Arial", 60)
label = myfont.render("Hello Pygame!", 1, (255, 255, 0))
clock = pygame.time.Clock()
FPS = 30
while True:
#allows user to exit the screen
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
# this code should be ran every frame
window.fill((0, 0, 0))
window.blit(label, (100, 100))
pygame.display.update()
clock.tick(FPS)
I hope that this answer has helped you and if you have any further questions please feel free to post a comment below!
I'm slowly trying to get to know pygame and write my first game in it and honestly, I didn't expect problems so early. So far I've only set a display, that is supposed to be there indefinitely (I just wanted to try it out):
import pygame
pygame.init()
(width, height) = (1000, 700)
screen = pygame.display.set_mode((width, height))
while True:
pygame.display.flip()
But when the window appears it says it's "not responding". I tried deleting the loop so that display would just blink once and vanish, because programm would die immiedately after it's created, but I get the same "not responding" window. I'm using pygame 1.9.2 and python 3.5. I wonder if the trouble may be because of anaconda - the window is opened as subcart for anaconda by default.
Edit: So far I discovered that when I open it not from spyder, but just click on a file it works just fine. Is there any way to make it work by simple run and compile while in spyder or it's just how it's supposed to work?
Add this to your loop. For me the only time it isnt responding is when I click the X and this could be to do with the fact that pygame doesn't know what to do when that happens.
import sys
for evt in pygame.event.get():
if evt.type == pygame.QUIT:
pygame.quit()
sys.exit()
#Try This
import pygame
(width, height) = (1000, 700)
screen=pygame.display.set_mode((width, height))
pygame.display.update()
while True:
for event in pygame.event.get():``
if event.type == pygame.QUIT:
pygame.quit()
quit()
I have done research about this problem, on internet, but there was no solution for my case... The window freezes when i try to close it with (X) button.
And as I said I haven't came across any solution on other posts, so I came here to ask for help. Thank you.
#!/usr/bin/python
import sys
import pygame
# initialize
pygame.init()
# colors
black = (0,0,0)
white = (255,255,255)
red = (255,0,0)
green = (0,255,0)
# window size
w_size = [700,500]
main_screen = pygame.display.set_mode(w_size)
# Window info
pygame.display.set_caption("Cancer Cell")
# manage screen update time
clock=pygame.time.Clock()
#background image
bg_img = pygame.image.load("/img/bg_img.png").convert()
# Main loop
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# GAME LOGIC - BEGINNING
# -------- DRAWINGS - BEGINNING --------
main_screen.blit(bg_img, [0,0])
# -------- DRAWINGS - END ----------
# update screen
pygame.display.flip()
clock.tick(20) # 20 FPS limit for loop.
pygame.quit()
Your code work perfectly well on my platform.
My platform:
Scientific Linux 7 (RHEL 7)
Python: 3.4.3
Pygame Version: 1.9.2b8
Window Manager: Gnome3
There is also probably bug in your code.
The "/img/bg_img.png" suggest absolute path, it possible, but very uncommon :).
Works pretty nicely for me. See the demo below:
Not only does your code work as expected on linux Mate 17, python 2.7.6 but it also works with sys.exit() instead of pygame.quit() or nothing at all i.e. no sys.exit() or pygame.quit()
So it turns out that the IDLE is what was causing the problem...
I tried to run the code from commandline and it worked perfectly!
The IDLE that I (was) using is called Wing101.