Creating A Pygame Window
Creating A Pygame Window
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:
The complete code for this tutorial is shown at the bottom of this page.
import pygame
We can now create a Pygame window object (which I've called 'screen')
usingpygame.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:
2 (width, height) = (300, 200)
3 screen = pygame.display.set_mode((width, height))
4
pygame.display.flip()
If you now run this program, youll 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.
5
6
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.
running = True
while running:
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 isnt normally a major
problem but it can stop the Pygame window from closing properly. If so,
adding pygame.quit() should solve the problem.
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.
5
background_colour = (255,255,255)
screen.fill(background_colour)
import pygame
02
03
background_colour = (255,255,255)
04
05
06
07
pygame.display.set_caption('Tutorial 1')
08
screen.fill(background_colour)
09
10
pygame.display.flip()
11
12
13
14
15
16
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):
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.