- Pygame Window Closing Automatically
- Pygame Window Closing Automatically Change
- Pygame Window Not Closing
- Pygame Window Closing Automatically Download
- Python Opens And Closes
Pygame.display.quit Uninitialize the display module quit - None This will shut down the entire display module. Super bounce out free. This means any active displays will be closed. This will also be handled automatically when the program exits.
pygame.display.init | — | Initialize the display module |
pygame.display.quit | — | Uninitialize the display module |
pygame.display.get_init | — | Returns True if the display module has been initialized |
pygame.display.set_mode | — | Initialize a window or screen for display |
pygame.display.get_surface | — | Get a reference to the currently set display surface |
pygame.display.flip | — | Update the full display Surface to the screen |
pygame.display.update | — | Update portions of the screen for software displays |
pygame.display.get_driver | — | Get the name of the pygame display backend |
pygame.display.Info | — | Create a video display information object |
pygame.display.get_wm_info | — | Get information about the current windowing system |
pygame.display.list_modes | — | Get list of available fullscreen modes |
pygame.display.mode_ok | — | Pick the best color depth for a display mode |
pygame.display.gl_get_attribute | — | Get the value for an OpenGL flag for the current display |
pygame.display.gl_set_attribute | — | Request an OpenGL display attribute for the display mode |
pygame.display.get_active | — | Returns True when the display is active on the screen |
pygame.display.iconify | — | Iconify the display surface |
pygame.display.toggle_fullscreen | — | Switch between fullscreen and windowed displays |
pygame.display.set_gamma | — | Change the hardware gamma ramps |
pygame.display.set_gamma_ramp | — | Change the hardware gamma ramps with a custom lookup |
pygame.display.set_icon | — | Change the system image for the display window |
pygame.display.set_caption | — | Set the current window caption |
pygame.display.get_caption | — | Get the current window caption |
pygame.display.set_palette | — | Set the display color palette for indexed displays |
pygame.display.get_num_displays | — | Return the number of displays |
pygame.display.get_window_size | — | Return the size of the window or screen |
pygame.display.get_allow_screensaver | — | Return whether the screensaver is allowed to run. |
pygame.display.set_allow_screensaver | — | Set whether the screensaver may run |
- Dec 21, 2020 pygame.init # Here init stands for initialization of the package. This will attempt to initialize all the pygame modules for you. Not all pygame modules need to be initialized, but this will automatically initialize the ones that do. You can also easily initialize each pygame module by hand. Creating windows screen.
- I'm having troubles with my pygame window immediately closing, even though its encased in a 'While True:' loop. Import os import pygame import sys import random import Projectile import Enemy import Player # Define constants WHITE = (255, 255, 255) BLACK = (0, 0, 0) RED = (255, 0, 0) GREY = (30, 30, 30) # Center the game window & start the environment, set up display os.environ'SDLVIDEO.
This module offers control over the pygame display. Pygame has a single displaySurface that is either contained in a window or runs full screen. Once youcreate the display you treat it as a regular Surface. Changes are notimmediately visible onscreen; you must choose one of the two flipping functionsto update the actual display.
The origin of the display, where x = 0 and y = 0, is the top left of thescreen. Both axes increase positively towards the bottom right of the screen.
The pygame display can actually be initialized in one of several modes. Bydefault, the display is a basic software driven framebuffer. You can requestspecial modules like hardware acceleration and OpenGL support. These arecontrolled by flags passed to pygame.display.set_mode()
.
Pygame can only have a single display active at any time. Creating a new onewith pygame.display.set_mode()
will close the previous display. If precisecontrol is needed over the pixel format or display resolutions, use thefunctions pygame.display.mode_ok()
, pygame.display.list_modes()
, andpygame.display.Info()
to query information about the display.
Once the display Surface is created, the functions from this module affect thesingle existing display. The Surface becomes invalid if the module isuninitialized. If a new display mode is set, the existing Surface willautomatically switch to operate on the new display.
When the display mode is set, several events are placed on the pygame eventqueue. pygame.QUIT
is sent when the user has requested the program toshut down. The window will receive pygame.ACTIVEEVENT
events as the displaygains and loses input focus. If the display is set with thepygame.RESIZABLE
flag, pygame.VIDEORESIZE
events will be sent when theuser adjusts the window dimensions. Hardware displays that draw direct to thescreen will get pygame.VIDEOEXPOSE
events when portions of the window mustbe redrawn.
In pygame 2, there is a new type of event called pygame.WINDOWEVENT
thatis meant to replace all window related events like pygame.VIDEORESIZE
,pygame.VIDEOEXPOSE
and pygame.ACTIVEEVENT
.
Note that the WINDOWEVENT API is considered experimental, and may change infuture releases.
The new events of type pygame.WINDOWEVENT
have an event
attribute thatcan take the following values.
If SDL version used is less than 2.0.5, the last two values WINDOWEVENT_TAKE_FOCUS
and WINDOWEVENT_HIT_TEST
will not work.See the SDL implementation (in C programming) of the sameover here.
Some display environments have an option for automatically stretching allwindows. When this option is enabled, this automatic stretching distorts theappearance of the pygame window. In the pygame examples directory, there isexample code (prevent_display_stretching.py) which shows how to disable thisautomatic stretching of the pygame display on Microsoft Windows (Vista or newerrequired).
pygame.display.
init
()¶Initializes the pygame display module. The display module cannot do anythinguntil it is initialized. This is usually handled for you automatically whenyou call the higher level pygame.init()
.
Pygame will select from one of several internal display backends when it isinitialized. The display mode will be chosen depending on the platform andpermissions of current user. Before the display module is initialized theenvironment variable SDL_VIDEODRIVER
can be set to control which backendis used. The systems with multiple choices are listed here.
On some platforms it is possible to embed the pygame display into an alreadyexisting window. To do this, the environment variable SDL_WINDOWID
mustbe set to a string containing the window id or handle. The environmentvariable is checked when the pygame display is initialized. Be aware thatthere can be many strange side effects when running in an embedded display.
It is harmless to call this more than once, repeated calls have no effect.
pygame.display.
quit
()¶This will shut down the entire display module. This means any activedisplays will be closed. This will also be handled automatically when theprogram exits.
It is harmless to call this more than once, repeated calls have no effect.
pygame.display.
get_init
()¶Returns True if the module is currently initialized.
pygame.display.
set_mode
()¶This function will create a display Surface. The arguments passed in arerequests for a display type. The actual created display will be the bestpossible match supported by the system.
The size argument is a pair of numbers representing the width andheight. The flags argument is a collection of additional options. The depthargument represents the number of bits to use for color.
The Surface that gets returned can be drawn to like a regular Surface butchanges will eventually be seen on the monitor.
If no size is passed or is set to (0,0)
and pygame uses SDL
version 1.2.10 or above, the created Surface will have the same size as thecurrent screen resolution. If only the width or height are set to 0
, theSurface will have the same width or height as the screen resolution. Using aSDL
version prior to 1.2.10 will raise an exception.
It is usually best to not pass the depth argument. It will default to thebest and fastest color depth for the system. If your game requires aspecific color format you can control the depth with this argument. Pygamewill emulate an unavailable color depth which can be slow.
When requesting fullscreen display modes, sometimes an exact match for therequested size cannot be made. In these situations pygame will selectthe closest compatible match. The returned surface will still always matchthe requested size.
On high resolution displays(4k, 1080p) and tiny graphics games (640x480)show up very small so that they are unplayable. SCALED scales up the windowfor you. The game thinks it's a 640x480 window, but really it can be bigger.Mouse events are scaled for you, so your game doesn't need to do it. Notethat SCALED is considered an experimental API and may change in futurereleases.
The flags argument controls which type of display you want. There areseveral to choose from, and you can even combine multiple types using thebitwise or operator, (the pipe '|' character). If you pass 0
or no flagsargument it will default to a software driven window. Here are the displayflags you will want to choose from:
Pygame 2 has the following additional flags available.
New in pygame 2.0.0: SCALED
, SHOWN
and HIDDEN
By setting the vsync
parameter to 1
, it is possible to get a displaywith vertical sync, but you are not guaranteed to get one. The request onlyworks at all for calls to set_mode()
with the pygame.OPENGL
orpygame.SCALED
flags set, and is still not guaranteed even with one ofthose set. What you get depends on the hardware and driver configurationof the system pygame is running on. Here is an example usage of a callto set_mode()
that may give you a display with vsync:
Vsync behaviour is considered experimental, and may change in future releases.
New in pygame 2.0.0: vsync
Basic example:
The display index 0
means the default display is used.
Changed in pygame 1.9.5: display
argument added
pygame.display.
get_surface
()¶Return a reference to the currently set display Surface. If no display modehas been set this will return None.
pygame.display.
flip
()¶This will update the contents of the entire display. If your display mode isusing the flags pygame.HWSURFACE
and pygame.DOUBLEBUF
, this willwait for a vertical retrace and swap the surfaces. If you are using adifferent type of display mode, it will simply update the entire contents ofthe surface.
When using an pygame.OPENGL
display mode this will perform a gl bufferswap.
pygame.display.
update
()¶This function is like an optimized version of pygame.display.flip()
forsoftware displays. It allows only a portion of the screen to updated,instead of the entire area. If no argument is passed it updates the entireSurface area like pygame.display.flip()
.
You can pass the function a single rectangle, or a sequence of rectangles.It is more efficient to pass many rectangles at once than to call updatemultiple times with single or a partial list of rectangles. If passing asequence of rectangles it is safe to include None values in the list, whichwill be skipped.
This call cannot be used on pygame.OPENGL
displays and will generate anexception.
pygame.display.
get_driver
()¶Pygame chooses one of many available display backends when it isinitialized. This returns the internal name used for the display backend.This can be used to provide limited information about what displaycapabilities might be accelerated. See the SDL_VIDEODRIVER
flags inpygame.display.set_mode()
to see some of the common options.
pygame.display.
Info
()¶Creates a simple object containing several attributes to describe thecurrent graphics environment. If this is called beforepygame.display.set_mode()
some platforms can provide information aboutthe default display mode. This can also be called after setting the displaymode to verify specific display options were satisfied. The VidInfo objecthas several attributes:
pygame.display.
get_wm_info
()¶Creates a dictionary filled with string keys. The strings and values arearbitrarily created by the system. Some systems may have no information andan empty dictionary will be returned. Most platforms will return a 'window'key with the value set to the system id for the current display.
New in pygame 1.7.1.
pygame.display.
list_modes
()¶This function returns a list of possible sizes for a specified colordepth. The return value will be an empty list if no display modes areavailable with the given arguments. A return value of -1
means thatany requested size should work (this is likely the case for windowedmodes). Mode sizes are sorted from biggest to smallest.
If depth is 0
, the current/best color depth for the display is used.The flags defaults to pygame.FULLSCREEN
, but you may need to addadditional flags for specific fullscreen modes.
The display index 0
means the default display is used.
pygame.display.
mode_ok
()¶This function uses the same arguments as pygame.display.set_mode()
. Itis used to determine if a requested display mode is available. It willreturn 0
if the display mode cannot be set. Otherwise it will return apixel depth that best matches the display asked for.
Usually the depth argument is not passed, but some platforms can supportmultiple display depths. If passed it will hint to which depth is a bettermatch.
The most useful flags to pass will be pygame.HWSURFACE
,pygame.DOUBLEBUF
, and maybe pygame.FULLSCREEN
. The function willreturn 0 if these display flags cannot be set.
The display index 0
means the default display is used.
pygame.display.
gl_get_attribute
()¶After calling pygame.display.set_mode()
with the pygame.OPENGL
flag,it is a good idea to check the value of any requested OpenGL attributes. Seepygame.display.gl_set_attribute()
for a list of valid flags.
pygame.display.
gl_set_attribute
()¶When calling pygame.display.set_mode()
with the pygame.OPENGL
flag,Pygame automatically handles setting the OpenGL attributes like color anddouble-buffering. OpenGL offers several other attributes you may want controlover. Pass one of these attributes as the flag, and its appropriate value.This must be called before pygame.display.set_mode()
.
Many settings are the requested minimum. Creating a window with an OpenGL contextwill fail if OpenGL cannot provide the requested attribute, but it may for examplegive you a stencil buffer even if you request none, or it may give you a largerone than requested.
The OPENGL
flags are:
GL_MULTISAMPLEBUFFERS
Whether to enable multisampling anti-aliasing.Defaults to 0 (disabled).
Set GL_MULTISAMPLESAMPLES
to a valueabove 0 to control the amount of anti-aliasing.A typical value is 2 or 3.
GL_STENCIL_SIZE
GL_DEPTH_SIZE
GL_STEREO
GL_BUFFER_SIZE
GL_CONTEXT_PROFILE_MASK
Sets the OpenGL profile to one of these values:
GL_ACCELERATED_VISUAL
pygame.display.
get_active
()¶Returns True when the display Surface is considered activelyrenderable on the screen and may be visible to the user. This isthe default state immediately after pygame.display.set_mode()
.This method may return True even if the application is fully hiddenbehind another application window.
This will return False if the display Surface has been iconified orminimized (either via pygame.display.iconify()
or via an OSspecific method such as the minimize-icon available on mostdesktops).
The method can also return False for other reasons without theapplication being explicitly iconified or minimized by the user. Anotable example being if the user has multiple virtual desktops andthe display Surface is not on the active virtual desktop.
Note
This function returning True is unrelated to whether theapplication has input focus. Please seepygame.key.get_focused()
and pygame.mouse.get_focused()
for APIs related to input focus.
pygame.display.
iconify
()¶Request the window for the display surface be iconified or hidden. Not allsystems and displays support an iconified display. The function will returnTrue if successful.
When the display is iconified pygame.display.get_active()
will returnFalse
. The event queue should receive an ACTIVEEVENT
event when thewindow has been iconified. Additionally, the event queue also recieves aWINDOWEVENT_MINIMIZED
event when the window has been iconified on pygame 2.
pygame.display.
toggle_fullscreen
()¶Switches the display window between windowed and fullscreen modes.Display driver support is not great when using pygame 1, but withpygame 2 it is the most reliable method to switch to and from fullscreen.
Supported display drivers in pygame 1:
Supported display drivers in pygame 2:
- windows (Windows)
- x11 (Linux/Unix)
- wayland (Linux/Unix)
- cocoa (OSX/Mac)
pygame.display.
set_gamma
()¶Set the red, green, and blue gamma values on the display hardware. If thegreen and blue arguments are not passed, they will both be the same as red.Not all systems and hardware support gamma ramps, if the function succeedsit will return True
.
A gamma value of 1.0
creates a linear color table. Lower values willdarken the display and higher values will brighten.
pygame.display.
set_gamma_ramp
()¶Set the red, green, and blue gamma ramps with an explicit lookup table. Eachargument should be sequence of 256 integers. The integers should rangebetween 0
and 0xffff
. Not all systems and hardware support gammaramps, if the function succeeds it will return True
.
Pygame Window Closing Automatically
pygame.display.
set_icon
()¶Sets the runtime icon the system will use to represent the display window.All windows default to a simple pygame logo for the window icon.
You can pass any surface, but most systems want a smaller image around32x32. The image can have colorkey transparency which will be passed to thesystem.
Some systems do not allow the window icon to change after it has been shown.This function can be called before pygame.display.set_mode()
to createthe icon before the display mode is set.
pygame.display.
set_caption
()¶If the display has a window title, this function will change the name on thewindow. Some systems support an alternate shorter title to be used forminimized displays.
pygame.display.
get_caption
()¶Returns the title and icontitle for the display Surface. These will often bethe same value.
pygame.display.
set_palette
()¶This will change the video display color palette for 8-bit displays. Thisdoes not change the palette for the actual display Surface, only the palettethat is used to display the Surface. If no palette argument is passed, thesystem default palette will be restored. The palette is a sequence ofRGB
triplets.
pygame.display.
get_num_displays
()¶Returns the number of available displays. This is always 1 if returns a major version number below 2.
pygame.display.
get_window_size
()¶Returns the size of the window initialized with .This may differ from the size of the display surface if SCALED
is used.
pygame.display.
get_allow_screensaver
()¶Return whether screensaver is allowed to run whilst the app is running.Default is False
.By default pygame does not allow the screensaver during game play.
Note
Some platforms do not have a screensaver or supportdisabling the screensaver. Please see forcaveats with screensaver support.
pygame.display.
set_allow_screensaver
()¶Change whether screensavers should be allowed whilst the app is running.The default is False.By default pygame does not allow the screensaver during game play.
If the screensaver has been disallowed due to this function, it will automaticallybe allowed to run when is called.
It is possible to influence the default value via the environment variableSDL_HINT_VIDEO_ALLOW_SCREENSAVER
, which can be set to either 0
(disable)or 1
(enable).
Note
Disabling screensaver is subject to platform support.When platform support is absent, this function willsilently appear to work even though the screensaver stateis unchanged. The lack of feedback is due to SDL notproviding any supported method for determining whetherit supports changing the screensaver state.SDL_HINT_VIDEO_ALLOW_SCREENSAVER
is available in SDL 2.0.2 or later.SDL1.2 does not implement this.
Pygame Window Closing Automatically Change
In Hello World we used the following line to create a Pygame window: screen = pygame.display.set_mode((640, 480), 0, 32)
The first parameter is the size of the window we want to create. A size of (640, 480) creates a small window that will fit comfortably on most desktops, but you can select a different size if you wish. Running in a window is great for debugging, but most games fill the entire screen with the action and don't have the usual borders and title bar. Full-screen mode is usually faster because your Pygame script doesn't have to cooperate with other windows on your desktop. To set full-screen mode, use the FULLSCREEN flag for the second parameter of set_mode:
screen = pygame.display.set_mode((640, 480), FULLSCREEN, 32)
■Caution If something goes wrong with your script in full-screen mode, it can sometimes be difficult to get back to your desktop. Therefore, it's best to test it in windowed mode first. You should also provide an alternative way to exit the script because the close button is not visible in full-screen mode.
When you go full screen, your video card will probably switch to a different video mode, which will change the width and height of the display, and potentially how many colors it can show at one time. Video cards only support a few combinations of size and number of colors, but Pygame will help you if you try to select a video mode that the card does not support directly. If the size of display you ask for isn't supported, Pygame will select the next size up and copy your display to the center of it, which may lead to black borders at the top and bottom of your display. To avoid these borders, select one of the standard resolutions that virtually all video cards support: (640, 480), (800, 600), or (1024, 768). To see exactly what resolutions your display supports, you can use pygame.display.list_modes(), which returns a list of tuples containing supported resolutions. Let's try this from the interactive interpreter:
>>> import pygame >>> pygame.init() >>> pygame.display.list_modes()
[(800, 600), (1280, 1024), (1280, 960), (1280, 800), (1280, 768), (1280, 720), (1152, 864), (1088, 612), (1024, 768), (960, 600), (848, 480), (800, 600), (720, 576), (720, 480), (640, 480), (640, 400), (512, 384), (480, 360), (400, 300), (320, 240), (320, 200), (640, 480)]
If the video card can't give you the number of colors you asked for, Pygame will convert colors in the display surface automatically to fit (which may result in a slight drop in image quality).
Listing 3-4 is a short script that demonstrates going from windowed mode to full-screen mode. If you press the F key, the display will fill the entire screen (there may be a delay of a few seconds while this happens). Press F a second time, and the display will return to a window.
Pygame Window Not Closing
Listing 3-4. Full-Screen Example background_image_filename = 'sushiplate.jpg'
Pygame Window Closing Automatically Download
import pygame from pygame.locals import * from sys import exit pygame.init()
screen = pygame.display.set_mode((640, 480), 0, 32) background = pygame.image.load(background_image_filename).convert()
Fullscreen = False while True:
for event in pygame.event.get(): if event.type QUIT: exit()
Fullscreen = not Fullscreen if Fullscreen:
Python Opens And Closes
screen = pygame.display.set_mode((640 else:
screen = pygame.display.set_mode((640
screen.blit(background, (0,0)) pygame.display.update()
Continue reading here: Additional Display Flags
Was this article helpful?