Pygame Window Closing Automatically

  1. Pygame Window Keeps Closing
  2. Pygame Window Closing Automatically Change
  3. Pygame Window Closing Automatically Reset
  4. Pygame Window Not Closing
  5. Pygame Window Closes Immediately
  6. Pygame Window Code
  7. Python Opens And Closes

In this first tutorial, we'll cover the basics and write some boilerplate code for Pygame - code you will almost always write whenever you use Pygame. We will:

  • Create a Pygame window
  • Stop the window from immediately disappearing
  • Close the window in response to a quit event
  • Change the title and background colour of the window

Returns True if the pygame.displaypygame module to control the display window and screen module is. OPENGL flag, Pygame automatically handles setting. 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.

Note for Mac users: If you get a blank screen when using Pygame, take a look here to find a version of pygame that works.

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. I'm new to programming, python and pygame. This is some code I wrote to draw random colored rectangles on an 800 x 600 canvas. It does what I expected it to do but becomes unresponsive if I click anywhere on the window. I am on a 64 bit windows 7 system running 32 bit python 2.7 with the appropriate pygame 1.9.1.

The Pygame window

Since we are going to use the Pygame module, the first thing we need to do is import it.

We can now create a Pygame window object (which I've called 'screen') using pygame.display.set_mode(). This object requires two values that define the width and height of the window. Rather than use constants, we'll define two variables, width and height, which will make the program easier to change later on. Feel free to use any integers that suit you. In order to display the window, we use the flip() function:

If you now run this program, you’ll see a 300 x 200 pixel window appear and then promptly disappear. The problem is that once as the flip() function has been called, the end of the code is reached, so the program ends.

To keep the screen visible for as long as we want, we need to make sure the program doesn't end. We could do this by adding an infinite loop.

The problem with an infinite loop is that, by definition, it never ends. The program won't quit even if we want it to. If we try to close the window by clicking on the X, nothing happens. You have to use Ctrl + C in the command line to force the program to quit.

Closing the window

We want our window to persist until the user chooses to closes it. To achieve this, we monitor user inputs (known as 'events') using pygame.event.get(). This function returns a list of events which we can loop through and check to see whether any have the type QUIT. If we find such an event, we exit our loop, which is best done by changing a boolean variable (which I've called 'running').

The window now persists whilst 'running' is equal to True, which it will be until you close the window (by clicking the X). Note that if you use an IDE for Python programming, then it may interfere with Pygame. This isn’t normally a major problem but it can stop the Pygame window from closing properly. If so, adding pygame.quit() should solve the problem (Thanks to nf3 in the comments for mentioning this).

Changing the window's properties

Now we have a usable window, we can change its properties. For example, we can change its title using the set_caption() function.

We can change the background colour by filling the screen object. Colours are defined using a 3-tuple of integers from 0 to 255, for the red, green and blue values respectively. For example, white is (255,255,255). Changes need to be made before the flip() function is called.

The final program

The complete program, after a bit of rearrangement, should now look like this:

You can also find the complete code for this tutorial by clicking the Code on Github link at the top of the article.

Running the program should create a window that looks like this (on Windows XP).

It's not very exciting at the moment, but now we have a window that persists until we close it. In the next tutorial we'll draw some shapes in our window and start our simulation by creating a Particle object.

pygame module to control the display window and screen
pygame.display.initInitialize the display module
pygame.display.quitUninitialize the display module
pygame.display.get_initReturns True if the display module has been initialized
pygame.display.set_modeInitialize a window or screen for display
pygame.display.get_surfaceGet a reference to the currently set display surface
pygame.display.flipUpdate the full display Surface to the screen
pygame.display.updateUpdate portions of the screen for software displays
pygame.display.get_driverGet the name of the pygame display backend
pygame.display.InfoCreate a video display information object
pygame.display.get_wm_infoGet information about the current windowing system
pygame.display.list_modesGet list of available fullscreen modes
pygame.display.mode_okPick the best color depth for a display mode
pygame.display.gl_get_attributeGet the value for an OpenGL flag for the current display
pygame.display.gl_set_attributeRequest an OpenGL display attribute for the display mode
pygame.display.get_activeReturns True when the display is active on the screen
pygame.display.iconifyIconify the display surface
pygame.display.toggle_fullscreenSwitch between fullscreen and windowed displays
pygame.display.set_gammaChange the hardware gamma ramps
pygame.display.set_gamma_rampChange the hardware gamma ramps with a custom lookup
pygame.display.set_iconChange the system image for the display window
pygame.display.set_captionSet the current window caption
pygame.display.get_captionGet the current window caption
pygame.display.set_paletteSet the display color palette for indexed displays
pygame.display.get_num_displaysReturn the number of displays
pygame.display.get_window_sizeReturn the size of the window or screen
pygame.display.get_allow_screensaverReturn whether the screensaver is allowed to run.
pygame.display.set_allow_screensaverSet whether the screensaver may run

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_FOCUSand 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()
init() -> None

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()
quit() -> None

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 display module has been initialized

Pygame Window Keeps Closing

Returns True if the module is currently initialized.

pygame.display.set_mode()
set_mode(size=(0, 0), flags=0, depth=0, display=0, vsync=0) -> Surface

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.

Pygame window closing automatically lock

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 SDLversion 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()
Get a reference to the currently set display surface

Return a reference to the currently set display Surface. If no display modehas been set this will return None.

pygame.display.flip()
flip() -> None
Pygame

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()
Update portions of the screen for software displays
update(rectangle_list) -> None

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()
get_driver() -> name

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()
Info() -> VideoInfo

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()
Get information about the current windowing system

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()
list_modes(depth=0, flags=pygame.FULLSCREEN, display=0) -> list

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()
mode_ok(size, flags=0, depth=0, display=0) -> depth

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()
Get the value for an OpenGL flag for the current display

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()
Request an OpenGL display attribute for the display mode

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

Minimum bit size of the stencil buffer. Defaults to 0.

GL_DEPTH_SIZE

Minimum bit size of the depth buffer. Defaults to 16.

GL_STEREO

GL_BUFFER_SIZE

Minimum bit size of the frame buffer. Defaults to 0.

GL_CONTEXT_PROFILE_MASK

Sets the OpenGL profile to one of these values:

Pygame Window Closing Automatically Change

GL_ACCELERATED_VISUAL

Set to 1 to require hardware acceleration, or 0 to force software render.By default, both are allowed.
pygame.display.get_active()
Returns True when the display is active on the screen

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()
iconify() -> bool

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()
toggle_fullscreen() -> int

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_gamma(red, green=None, blue=None) -> bool

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()
Change the hardware gamma ramps with a custom lookup

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.display.set_icon()
set_icon(Surface) -> None

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()
set_caption(title, icontitle=None) -> None

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()
get_caption() -> (title, icontitle)

Returns the title and icontitle for the display Surface. These will often bethe same value.

pygame.display.set_palette()
Set the display color palette for indexed displays

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()
get_num_displays() -> int

Returns the number of available displays. This is always 1 if returns a major version number below 2.

pygame.display.get_window_size()
get_window_size() -> tuple

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()
get_allow_screensaver() -> bool

Pygame Window Closing Automatically Reset

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 Window Not Closing

pygame.display.set_allow_screensaver()
set_allow_screensaver(bool) -> None

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.

Pygame Window Closes Immediately

If the screensaver has been disallowed due to this function, it will automaticallybe allowed to run when is called.

Pygame Window Code

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

Python Opens And Closes

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.