Creating a Pygame window

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

The complete code for this tutorial is shown at the bottom of this page.

The Pygame window

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

import pygame

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:

(width, height) = (300, 200)
screen = pygame.display.set_mode((width, height))
pygame.display.flip()

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.

while True:
  pass

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 acheive 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').

running = True
while running:
  for event in pygame.event.get():
    if event.type == pygame.QUIT:
      running = False

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.

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.

pygame.display.set_caption('Tutorial 1')

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.

background_colour = (255,255,255)
screen.fill(background_colour)

The final program

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

import pygame

background_colour = (255,255,255)
(width, height) = (300, 200)

screen = pygame.display.set_mode((width, height))
pygame.display.set_caption('Tutorial 1')
screen.fill(background_colour)

pygame.display.flip()

running = True
while running:
  for event in pygame.event.get():
    if event.type == pygame.QUIT:
      running = False

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

A Pygame Window

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.

AttachmentSize
particle_tutorial_1.txt372 bytes

Comments

found your tutorial very useful and easy to follow.

As i code with Idle, was troubled with the bad closing habits of the app. After a internet search I found a simple unobstrusive solution:

after, and outside of the last 'while running' loop, place the instruction

pygame.quit ()

 

Cool. The closing error was the main reason I've avoided using an IDE. I might give it a go now, thanks.

Perfectly explained, convenient tools to get the code and graphically nice site.  It is helping me a lot, thank you very much.

Why is it that we use 

pygame.display.set_caption()
pygame.display.flip()

and not 

screen.set_caption()
screen.flip()
Like the website very much. Glad to see that I'm not the only one using Windows XP.

Hi PeterI love your work!  I am a physics technician and your star formation simulation programme is proving very popular with the teachers.It works without problem on the Raspberry Pi, but when I try to use it on a windows machine with Python 2.7.6 installed, it throws up an error "Traceback (most recent call last):  File "C:\Python27\window_opening.py", line 1, in <module>    import pygame  File "C:\Python27\lib\pygame.py", line 1    /*    ^SyntaxError: invalid syntax"Should I install an earlier version, if so, which one? Thank you

Hi William,

That's very cool that it works on Raspberry Pi. I'm glad you're enjoying the program. I have a 3D version online at Khan Academy if you're interested: https://www.khanacademy.org/cs/challenge-modeling-accretion-disks/1180451277

As for the problem you're having, it looks like there's a problem with the pygame.py file. Have you tried running any other programs that use Pygame or running python in the command line and typing import pygame? I'll check what the pygame file looks like on my Windows machine and see if I can work out what might be wrong, but it seems unlikely that I will be able to. I wrote the program using Python 2.7, so that's not the problem.

If you have any other problems, you can email me using the Contact Me button on the left hand side of the page.

Post new comment

The content of this field is kept private and will not be shown publicly.