Python Pygame tutorial + 36 Examples

Want to learn about Python pygame? Keep reading this Python pygame tutorial, I have explained with various pygame examples in Python and I hope this Python pygame tutorial for beginners will help you to learn Python pygame.

We will cover these topics:

  • What is Pygame in python?
  • How to install Pygame in python
  • Pygame module in python
  • Python Pygame example
  • How to put the screen in a specific spot in python pygame
  • How to get the size of python pygame window
  • How to resize a window in python pygame
  • How to draw a circle using python pygame
  • How to draw a rectangle using python pygame
  • How to draw a line using python pygame
  • How to draw an ellipse using python pygame
  • How to draw a polygon using python pygame
  • How to draw a triangle using python pygame
  • How to draw an arc using python pygame
  • How to get the font in python using pygame
  • How to display text in python pygame
  • Python how to make a text rectangle in pygame
  • How to move an object in python pygame
  • Draw design using the arrow keys in python pygame
  • How to scale an image in python pygame
  • How to display an image in python pygame
  • Python pygame error: No such file or directory while displaying an image
  • Resize the image in python pygame
  • How to add background image in python pygame
  • How to add an image to a background image in python pygame
  • How to change the screen background color in python pygame
  • How to terminate game in python pygame
  • How to add color breezing effect in python pygame
  • How to track mouse movement in python pygame
  • How to create buttons in python pygame
  • How to play audio in python with pygame
  • How to display message on screen on two lines python pygame
  • Python pygame animation
  • Python pygame snow animation
  • Python pygame animation with a circle
  • Python how to get user input in a pygame window
  • Python pygame animate a ball to move in a sine pattern
Table of Contents show

What is Pygame in python?

  • Python Pygame is a cross-platform set of python modules that are designed for creating video games.
  • It also includes graphics and sound libraries which is to be used for the Python programming language.
  • Pygame is suitable for creating any type of game.

You may like Python programming for the absolute beginner and Machine Learning using Python.

python pygame tutorial
python pygame tutorial

How to install Pygame in python

  • To install pygame in python, the first step is to make sure that you have a supported version of python.
  • Now, open the command line and write the following command on cmd.

Command to install pygame:

pip install pygame

Pygame module in python

Pygame has some module, pygame.draw is used for drawing shapes to a surface.

  • pygame.draw.circle – This function is used for drawing a circle around a point.
  • pygame.draw.rect – This function is used for drawing a rectangle shape.
  • pygame.draw.polygon – This function is used for drawing a shape with any number of sides.
  • pygame.draw.ellipse – This function is used for drawing a round shape inside a rectangle.
  • pygame.draw.line – This function is used for drawing a straight line.
  • pygame.draw.arc – This function draws a partial section of an ellipse.
  • pygame.draw.lines – This function draws the multiple contiguous line segments.

Python Pygame example

Now, in this Python pygame tutorial, let us see the example on python pygame.

  • Firstly import pygame, it provides access to the pygame framework and imports all functions.
  • The pygame.init() is used to initialize all the required modules of the pygame.
  • scr = pygame.display.set_mode((600,500)) is used to display a window of desired size. Here, width is 600 and height is 500.
  • pygame.display.set_caption(‘Pygame Window’) is used to define our display “caption”. So, we have given the name “Pygame Window”.
  • Here, done = False is just a variable that we set initially.
  • Now, we will run the loop, which will run unit it is done. So, we will use “done = True” to exits out of the window.
  • pygame.event.get() is used to empty the event queue. It is important to call, and if we do not call, then the window message will start to pile up, and it will become unresponsive.
  • pygame.QUIT is used to terminate the event when we click the close button of the window.
  • pygame.display.flip() shift the buffers. It is important to call this function in order to make any updates that we will make on the game screen.

Example:

import pygame  
pygame.init()  
scr = pygame.display.set_mode((600,500))  
pygame.display.set_caption('Pygame Window')
done = False  
while not done:  
    for event in pygame.event.get():  
        if event.type == pygame.QUIT:  
            done = True  
pygame.display.flip()  

In this output, we can see that the new window appear as an output with a caption.

Python Pygame example
Python Pygame example

You may like Python GUI Programming

How to put the screen in a specific spot in python pygame

Let’s see how to put the screen in a specific spot in python pygame.

  • To put the screen in the specific spot we will first import os, then we can import pygame and time module.
  • We will use SDL environment variables, so that environment variables can be set with the os.environ in python.
  • And the X and Y are set for a specific spot.
  • win_screen = pygame.display.set_mode((500,500)) is used to set the size and the time.sleep(2) wait for a while to show the window.

Example:

import os
import pygame
import time
X = 100
Y = 100
os.environ['SDL_VIDEO_WINDOW_POS'] = "%d,%d" % (X,Y)
pygame.init()
win_screen = pygame.display.set_mode((500,500))
time.sleep(2)

In this output, we can see that the new window appear in a specific spot in python pygame.

How to put the screen in a specific spot in python pygame
How to put the screen in a specific spot in python pygame

How to get the size of Python pygame window

Let’s see how to get the size of python pygame window.

  • Firstly import pygame, it provides access to the pygame framework and imports all functions.
  • The pygame.init() is used to initialize all the required modules of the pygame.
  • scr = pygame.display.set_mode() is used to form screen using this method.
  • To get the size of the screen we will use the “scr.get_size()” method.
  • Here, pygame.display.quit() is used to quit pygame, and print(x, y) is used for printing the value.

Example:

import pygame
pygame.init() 
scr = pygame.display.set_mode()
x, y = scr.get_size() 
pygame.display.quit() 
print(x, y) 

In the below output, you can see the size of python pygame window.

Output:

1366 768

How to resize a window in python pygame

Let’s see how to resize a window in python pygame.

  • Firstly import pygame, it provides access to the pygame framework and imports all functions.
  • To form a screen we will use pygame.display.set_mode() method with resizing using pygame.RESIZABLE.
  • pygame.display.set_caption(‘Resizable Window’) is used to set the title according to the user choice.
  • Then run the pygame using while, and to quit pygame after closing window we have used pygame.quit().

Example:

import pygame 
scr = pygame.display.set_mode((500, 400),pygame.RESIZABLE) 
pygame.display.set_caption('Resizable Window') 
running = True
while running: 
    for event in pygame.event.get(): 
        if event.type == pygame.QUIT: 
            running = False
pygame.quit() 

In this output, we can see the new window appears and we can resize the window accordingly.

How to resize a window in python pygame
How to resize a window in python pygame

In the below output, we can see that resize is done on the same window accordingly.

How to resize a window in python pygame
How to resize a window in python pygame

How to draw a circle using python pygame

Let’s see how to draw a circle using python pygame.

  • Firstly we will import pygame. The pygame.init() is used to initialize all the required modules of the pygame.
  • scr = pygame.display.set_mode((600,500)) is used to display a window of desired size. Here, width is 600 and height is 500.
  • Here, while is used to run until the user asks to quit.
  • Now, scr.fill((255, 255, 255)) is used to fill the background with white.
  • To draw the circle of red color we have used the “(200, 0, 0)” parameter, “(250, 250)” is used for specifying the center coordinates of the circle, and “80” is the radius of a circle to draw in pixels.
  • pygame.display.flip() is used to update the content of the display to the screen.

Example:

import pygame
pygame.init()
scr = pygame.display.set_mode((600, 500))
running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
    scr.fill((255, 255, 255))
    pygame.draw.circle(scr, (200, 0, 0), (250, 250), 80)
    pygame.display.flip()
pygame.quit()

In this output, we can see the new window appears and the circle with red color appears on the pygame window.

How to draw a circle using python pygame
How to draw a circle using python pygame

How to draw a rectangle using python pygame

  • Firstly we will import pygame. The pygame.init() is used to initialize all the required modules of the pygame.
  • scr = pygame.display.set_mode((500,500)) is used to display a window of desired size. Here, width is 500 and height is 500.
  • Here, color = (0,0,255) is used for lightblue color.
  • For drawing a rectangle we will use “pygame.draw.rect(scr, color, pygame.Rect(60, 60, 100, 100))”.
  • pygame.display.flip() is used to update the content of the display to the screen. To hold the screen we have used “while True: pass”.

Example:

import pygame 
pygame.init() 
scr = pygame.display.set_mode((500,500)) 
color = (0,0,255) 
pygame.draw.rect(scr, color, pygame.Rect(60, 60, 100, 100)) 
pygame.display.flip() 
while True:
  pass

In this output, we can see that the new window appears, and the rectangle is drawn on the pygame window.

How to draw a rectangle using python pygame
How to draw a rectangle using python pygame

How to draw a line using python pygame

Now, we will see how to draw a line using python pygame

  • Firstly we will import pygame. The pygame.init() is used to initialize all the required modules of the pygame.
  • scr = pygame.display.set_mode((500,500)) is used to display a window of desired size. Here, width is 500 and height is 500.
  • Here, color = (0,255,0) is used for green color.
  • pygame.draw.line(scr, color, (40, 300), (140, 300), 6) is used for drawing a line. Here, the parameter “(40, 300)” is used for the start point, “(140, 300)” is used for the end point, and “6” is used for the thickness of a line.
  • pygame.display.flip() is used to update the content of the display to the screen. To hold the screen we have used “while True: pass”.

Example:

import pygame 
pygame.init() 
scr = pygame.display.set_mode((500,500)) 
color = (0,255,0) 
pygame.draw.line(scr, color, (40, 300), (140, 300), 6)
pygame.display.flip() 
while True:
  pass

In this output, we can see that the new window appears, and the line is drawn on the pygame window.

How to draw a line using python pygame
How to draw a line using python pygame

How to draw an ellipse using python pygame

Let’s draw an ellipse using python pygame

  • Firstly, we will import pygame. The pygame.init() is used to initialize all the required modules of the pygame.
  • scr = pygame.display.set_mode((500,500)) is used to display a window of desired size. Here, width is 500 and height is 500.
  • Here, white = (255,255,255) is used for white color.
  • pygame.draw.ellipse(scr, white , (350, 250, 60, 90), 4) is used for drawing an ellipse. Here, (350, 250, 60, 90) is used for bounding ellipse, and “4” is used for thickness.
  • pygame.display.flip() is used to update the content of the display to the screen. To hold the screen we have used “while True: pass”.

Example:

import pygame 
pygame.init() 
scr = pygame.display.set_mode((500,500)) 
white = (255,255,255) 
pygame.draw.ellipse(scr, white , (350, 250, 60, 90), 4)
pygame.display.flip() 
while True:
  pass

In this output, we can see that the new window appears, and the ellipse is drawn on the pygame window.

How to draw an ellipse using python pygame
How to draw an ellipse using python pygame

How to draw a polygon using python pygame

  • Firstly, we will import pygame. The pygame.init() is used to initialize all the required modules of the pygame.
  • scr = pygame.display.set_mode((600,500)) is used to display a window of desired size. Here, width is 600 and height is 500.
  • Here, purple = (102,0,102) is used for purple color.
  • pygame.draw.polygon(scr, purple,((146, 0), (291, 106),(236, 277), (56, 277), (0, 106))) is used for drawing polygon.
  • pygame.display.flip() is used to update the content of the display to the screen. To hold the screen we have used “while True: pass”.

Example:

import pygame 
pygame.init() 
scr = pygame.display.set_mode((600,500)) 
purple = (102, 0, 102) 
pygame.draw.polygon(scr, purple, 
                    ((146, 0), (291, 106),(236, 277), (56, 277), (0, 106))) 
pygame.display.flip() 
while True:
  pass

In this output, we can see that the new window appears, and the polygon is drawn on the pygame window.

How to draw a polygon using python pygame
How to draw a polygon using python pygame

How to draw a triangle using python pygame

Here, we will see how to draw a triangle using python pygame

  • Firstly, we will import pygame. The pygame.init() is used to initialize all the required modules of the pygame.
  • scr = pygame.display.set_mode((500,500)) is used to display a window of desired size. Here, width is 500 and height is 500.
  • Here, lightgreen = (0,255,0) is used for lightgreen color.
  • pygame.draw.polygon(scr, lightgreen, ((100, 100), (0, 200),(200, 200)), 3) is used for drawing a triangle using the polygon function, and “3” is the parameter used for the thickness of the triangle.
  • pygame.display.flip() is used to update the content of the display to the screen. To hold the screen we have used “while True: pass”.

Example:

import pygame 
pygame.init() 
scr = pygame.display.set_mode((500,500)) 
lightgreen = (0, 255, 0) 
pygame.draw.polygon(scr, lightgreen, ((100, 100), (0, 200),(200, 200)), 3) 
pygame.display.flip() 
while True:
  pass

In this output, we can see that the new window appears, and the triangle is drawn on the pygame window.

How to draw a triangle using python pygame
How to draw a triangle using python pygame

How to draw an arc using python pygame

Here, we will see how to draw an arc using python pygame

  • Firstly, we will import pygame. The pygame.init() is used to initialize all the required modules of the pygame.
  • scr = pygame.display.set_mode((500,500)) is used to display a window of desired size. Here, width is 500 and height is 500.
  • Also, we have given pi = 3.14. To draw an arc we have used pygame.draw.arc(scr, white, [210, 100, 250, 200], 0, pi / 2, 2).
  • pygame.display.flip() is used to update the content of the display to the screen. To hold the screen we have used “while True: pass”.

Example:

import pygame 
pygame.init() 
scr = pygame.display.set_mode((500,500))
pi = 3.14 
white = (255, 255, 255) 
pygame.draw.arc(scr, white, [210, 100, 250, 200], 0, pi / 2, 2)  
pygame.display.flip() 
while True:
  pass

In this output, we can see that the new window appears, and the arc is drawn on the pygame window.

How to draw an arc using python pygame
How to draw an arc using python pygame

How to get the font in python using pygame

  • Firstly, we will import pygame and sys. The pygame.init() is used to initialize all the required modules of the pygame.
  • screen= pygame.display.set_mode((500,400)) is used to display a window of desired size. Here, the width is 500 and the height is 400.
  • For the font, we have used the SysFont() function in which the name of the fonts and font size are given. As you can see we have created several types of fonts.
  • For instance, we have created a font type for text using a small font size. We have another font type for fun with little big font and for a much larger font, we have game_end.
  • Now we have to render the chosen font and create a surface object. While rendering we have to decide the color as well. The true parameters are used to make edges smoother.
  • So, the final step is to display the object onscreen. The surface.blit() function is used to display. It has two parameters, first the surface object and second a pair of coordinates to draw the surface object.

Example:

import pygame, sys
pygame.init()
screen = pygame.display.set_mode((500, 400))
font = pygame.font.SysFont('arial', 18)
new_font = pygame.font.SysFont('Timesnewroman', 25)
new_font2 = pygame.font.SysFont('impact', 70)
text = font.render("Welcome to Pygame Example!",True, (0,255,0))
fun = new_font.render("Enjoy with games", True, (0,255,255))
game_end = new_font2.render("Game Ends", True, (255,0,0))
while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit() 
    screen.fill((255, 255, 255)) 
    screen.blit(text, (40,60))
    screen.blit(fun, (40,90))
    screen.blit(game_end, (40,140))
    pygame.display.flip()

In this output, we can see that the new window appears, with the text font in python using pygame

How to get the font in python using pygame
How to get the font in python using pygame

How to display text in python pygame

Now, we will see how to display text in python pygame

  • Firstly, we will import pygame. The pygame.init() is used to initialize all the required modules of the pygame.
  • scr = pygame.display.set_mode((700,600)) is used to display a window of desired size. Here, the width is 700 and the height is 600.
  • For font we have used “pygame.font.SysFont(“Arial”, 80)”.
  • The syntax used to render the text is render(text, antialias, color, background=None). This function is used to draw text on a new surface.
  • scr.fill((0, 0, 0)) is used for black color for the background.
  • The scr.blit() method of pygame display surface object. Copying the text surface object to the display surface object using the blit() method.

Example:

import pygame  
pygame.init()  
scr = pygame.display.set_mode((700, 600))  
done = False  
font = pygame.font.SysFont("Arial", 80)  
text = font.render("Welcome to Pygame", True, (255, 100, 100))
while not done:  
    for event in pygame.event.get():  
        if event.type == pygame.QUIT:  
            done = True  
        if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:  
            done = True  
    scr.fill((0, 0, 0))  
    scr.blit(text,(320 - text.get_width()//2, 240 - text.get_height() // 2))  
    pygame.display.flip()  

In this output, we can see that the new window appears, and the text is written on the python pygame window.

How to display text in python pygame
How to display text in python pygame

Python how to make a text rectangle in pygame

  • Firstly, we will import pygame. The pygame.init() is used to initialize all the required modules of the pygame.
  • Now, we will define the value for white, red, black color. Also, assign the values to the X and Y variables.
  • Create the display surface object of specific dimension like display_surface = pygame.display.set_mode((X, Y)).
  • Set the name for pygame window “pygame.display.set_caption(‘Text Rectangle’)”.
  • To create a font object we will use the font.font() method with two parameters:
    • The first parameter is a font file that is present in pygame.
    • The second parameter is the size of the font.
  • Now create a text surface object in which text is drawn, using the render() method of pygame font object. Also, create a rectangular object for text surface using “textRect = text.get_rect()”.
  • Set the center of the rectangular object using “textRect.center = (X // 2, Y // 2)”.
  • Copying the text surface object to the display surface object using blit() method.
  • Show the display surface object on the pygame window using the display.update() method.

Example:

import pygame
pygame.init()
white = (255, 255, 255)
red = (255, 0, 0)
black = (0, 0, 0)
X = 500
Y = 400
display_surface = pygame.display.set_mode((X, Y))
pygame.display.set_caption('Text Rectangle')
font = pygame.font.Font('freesansbold.ttf', 32)
text = font.render('Python Pygame Tutorial', True, red, black)
textRect = text.get_rect()
textRect.center = (X // 2, Y // 2)
while True:
    display_surface.fill(white)
    display_surface.blit(text, textRect)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            quit()
        pygame.display.update()

In this output, we can see that the new window appears, and the text is in a rectangle in pygame

Python how to make a text rectangle in pygame
Python how to make a text rectangle in pygame

How to move an object in python pygame

Let us see how to move an object in python pygame.

  • Here, we will be learning how to move an object so that it moves horizontally when pressing the left or right arrow key on the keyboard, and it moves vertically when pressing the up or down arrow key.
  • Firstly, we will import pygame. The pygame.init() is used to initialize all the required modules of the pygame.
  • window = pygame.display.set_mode((600,600)) is used to display a window of desired size. Here, the width is 600 and the height is 600.
  • Now, we will set the pygame window name by using the pygame.display.set_caption(“Moving Object”).
  • x = 200 and y = 200 is the object current co-ordinates.
  • width = 20 and height = 20 is the dimension of the object. And vel = 10 is the speed of the object movement.
  • run = True indicates that pygame is running and while loop is used.
  • for event in pygame.event.get() is used to iterate over the list of event objects and if event.type == pygame.QUIT is the event of object for quitting the pygame and program.
  • The keys = pygame.key.get_pressed() stores keys pressed.
  • The left arrow key decrement in x co-ordinate and the right arrow key increment in x co-ordinate.
  • The up arrow key decrement in y co-ordinate and the down arrow key increment in y co-ordinate.
  • The window.fill((0, 0, 0)) is used to fill the object surface with black color.
  • pygame.draw.rect() is used to draw a rectangle. And pygame.display.update() refreshes the window.

Example:

import pygame   
pygame.init()  
window = pygame.display.set_mode((600, 600)) 
pygame.display.set_caption("Moving Object") 
x = 200
y = 200
width = 20
height = 20
vel = 10
run = True
while run: 
    pygame.time.delay(10) 
    for event in pygame.event.get(): 
        if event.type == pygame.QUIT: 
            run = False
    keys = pygame.key.get_pressed() 
    if keys[pygame.K_LEFT] and x>0: 
        x -= vel 
    if keys[pygame.K_RIGHT] and x<600-width: 
        x += vel 
    if keys[pygame.K_UP] and y>0: 
        y -= vel 
    if keys[pygame.K_DOWN] and y<600-height: 
        y += vel 
    window.fill((0, 0, 0)) 
    pygame.draw.rect(window, (255, 0, 0), (x, y, width, height)) 
    pygame.display.update()  
pygame.quit() 

In this output, we can see that the new window appears, and the object is at its initial position on the python pygame window.

How to move an object in python pygame
How to move an object in python pygame

In the below output, we can see that the new window appears, and the object is moved from the initial position by using the arrow key.

How to move an object in python pygame
How to move an object in python pygame

Draw design using the arrow keys in python pygame

Here, we will see how we can draw a design using the arrow keys in python pygame.

  • Here, we will see how we can make a design in pygame with the help of arrow keys. The marker will move horizontally when pressing the left or right arrow key on the keyboard, and it moves vertically when pressing the up or down arrow key.
  • Firstly, we will import pygame. The pygame.init() is used to initialize all the required modules of the pygame.
  • window = pygame.display.set_mode((600,600)) is used to display a window of desired size. Here, the width is 600 and the height is 600.
  • Now, we will set the pygame window name pygame.display.set_caption(“Drawing Design”).
  • x = 300 and y = 300 is the object current co-ordinates.
  • width = 20 and height = 20 is the dimension of the object. And vel = 10 is the speed of the object movement.
  • run = True indicates that pygame is running and while loop is used.
  • for event in pygame.event.get() is used to iterate over the list of event objects and if event.type == pygame.QUIT is the event of an object for quitting the pygame and program.
  • The keys = pygame.key.get_pressed() stores keys pressed.
  • The left arrow key decrement in x co-ordinate and the right arrow key increment in x co-ordinate.
  • The up arrow key decrement in y co-ordinate and the down arrow key increment in y co-ordinate.
  • pygame.draw.rect() is used to draw a rectangle. And pygame.display.update() refreshes the window.

Example:

import pygame 
pygame.init()   
window = pygame.display.set_mode((600, 600)) 
pygame.display.set_caption("Drawing Design") 
x = 300
y = 300
width = 20
height = 20
vel = 10
run = True
while run:  
    pygame.time.delay(10)  
    for event in pygame.event.get(): 
        if event.type == pygame.QUIT: 
            run = False
    keys = pygame.key.get_pressed() 
    if keys[pygame.K_LEFT] and x > 0: 
        x -= vel 
    if keys[pygame.K_RIGHT] and x < 600 - width: 
        x += vel 
    if keys[pygame.K_UP] and y > 0: 
        y -= vel 
    if keys[pygame.K_DOWN] and y < 600 - height: 
        y += vel 
    pygame.draw.rect(window, (255, 255, 255), (x, y, width, height)) 
    pygame.display.update() 
pygame.quit()  

In this output, we can see that the new window appears, and we have drawn a shape using the arrow keys in the pygame window.

Draw design using the arrow keys in python pygame
Draw design using the arrow keys in python pygame

How to scale an image in python pygame

Now, we will see how to scale an image in python pygame

  • To scale an image in python pygame we will use “pygame.transform.scale()”.
  • The pygame.transform.scale() will resize the image by passing the parameter with the width and height accordingly.
  • Here, we have used img = pygame.transform.scale(img,(400,400)) to scale an image.

Example:

import pygame 
pygame.init()  
pygame.display.set_caption('Image Scale')  
img = pygame.image.load("img.jpg") 
img = pygame.transform.scale(img,(400,400))
display = pygame.display.set_mode((500,500))
display.blit(img,[0,0])
pygame.display.update() 
while True:
  pass

In this output, we can see that the new window appears, and the scale for image is used in python pygame

How to scale an image in python pygame
How to scale an image in python pygame

How to display an image in python pygame

Let us see how to display an image in python pygame.

  • Firstly, we will import pygame. The pygame.init() is used to initialize all the required modules of the pygame.
  • Now, create a display surface object using pygame.display.set_caption() method of pygame.
  • Create an image surface object in which the image is drawn using pygame.image.load() method of pygame.
  • Copy the image surface object to the display surface object using the display.blit() method.
  • To display surface objects on the pygame window we have used display.update() method of pygame.
  • To hold the screen we have used “while True: pass”.

Example:

import pygame 
pygame.init()  
pygame.display.set_caption('Image')  
img = pygame.image.load("robotic.jpg") 
display = pygame.display.set_mode((600,600))
display.blit(img,[0,0])
pygame.display.update() 
while True:
  pass

In this output, we can see that the new window appears, and the image is displayed in the python pygame window.

How to display an image in python pygame
How to display an image in python pygame

Python pygame error: ‘No such file or directory’ while displaying an image

When we will run the below code to get the image on the screen then we may get the error “No such file or directory”.

Example:

import pygame 
pygame.init()  
pygame.display.set_caption('Image')  
img = pygame.image.load("robotic.jpg") 
display = pygame.display.set_mode((600,600))
display.blit(img,[0,0])
pygame.display.update() 
while True:
  pass

In the below output, we can see the error ‘No such file or directory‘.

Output:

Python pygame error: 'No such file or directory' while displaying an image
Python pygame error: ‘No such file or directory’ while displaying an image

Solution:

To solve this error we have to be in the same directory as your program will work provided that is the current working directory. We got this error because we were not in the same directory. So change the directory and then try to run it. And then you will be able to see the image on the window screen.

Resize the image in python pygame

Now, we will see how to resize the image in python pygame.

  • Firstly, we will import pygame. The pygame.init() is used to initialize all the required modules of the pygame.
  • Now, create a display surface object using pygame.display.set_caption() method of pygame.
  • Create an image surface object in which the image is drawn using pygame.image.load() method of pygame.
  • The pygame.transform.scale() will resize the image by passing the parameter with the width and height accordingly.
  • Copy the image surface object to the display surface object using the display.blit() method.
  • To display surface objects on the pygame window we have used display.update() method of pygame.
  • To hold the screen we have used “while True: pass”.

Example:

import pygame 
pygame.init()  
pygame.display.set_caption('Image')  
img = pygame.image.load("robotic.jpg") 
img = pygame.transform.scale(img,(500,500))
display = pygame.display.set_mode((600,600))
display.blit(img,[0,0])
pygame.display.update() 
while True:
  pass

In this output, we can see that the new window appears, and the resize of the image is done in the python pygame window.

Resize the image in python pygame
Resize the image in python pygame

How to add background image in python pygame

Let’s see how to add background image in python pygame.

  • Firstly, we will import pygame. The pygame.init() is used to initialize all the required modules of the pygame.
  • Now, create a display surface object using pygame.display.set_caption() method of pygame.
  • To load the background image we will use background = pygame.image.load(“background.jpeg”) method in pygame. The load(filename) filename is the full path of a file name to load.
  • The pygame.transform.scale() will resize the image by passing the parameter with the width and height accordingly.
  • The display.blit(background,[0,0]) method call the blit method to draw an image on the screen.
  • To display surface objects on the pygame window we have used display.update() method of pygame.
  • To hold the screen we have used “while True: pass”.

Example:

pygame.init()  
pygame.display.set_caption('Pygame Window')  
background = pygame.image.load("background.jpeg") 
background = pygame.transform.scale(background,(500,500))
display = pygame.display.set_mode((500,500))
display.blit(background,[0,0])
pygame.display.update() 
while True:
  pass

In this output, we can see that the new window appears, and the background image is added in the python pygame window.

How to add background image in python pygame
How to add background image in python pygame

How to add an image to a background image in python pygame

  • Firstly, we will import pygame. The pygame.init() is used to initialize all the required modules of the pygame.
  • Now, create a display surface object using pygame.display.set_caption() method of pygame.
  • To load the background image we will use background = pygame.image.load(“background.jpeg”) method in pygame. The load(filename) filename is the full path of a file name to load.
  • To add a new image to the background we will use img = pygame.image.load(“Image.png”) method in pygame.
  • The pygame.transform.scale() will resize the image by passing the parameter with the width and height accordingly.
  • The display.blit(background,[0,0]) method call the blit method to draw a background image on the screen.
  • Also, display.blit(img,[150,150]) method call the blit method to draw a new image on the background image.
  • To display surface objects on the pygame window we have used display.update() method of pygame.
  • To hold the screen we have used “while True: pass”.

Example:

import pygame 
pygame.init()  
pygame.display.set_caption('Pygame Window')  
background = pygame.image.load("background.jpeg") 
img = pygame.image.load("Image.png") 
background = pygame.transform.scale(background,(500,500))
img = pygame.transform.scale(img,(200,200))
display = pygame.display.set_mode((500,500))
display.blit(background,[0,0])
display.blit(img,[150,150])
pygame.display.update() 
while True:
  pass

In this output, we can see that the new window appears, and the new image is added to a background image in python pygame.

How to add an image to a background image in python pygame
How to add an image to a background image in python pygame

How to change the screen background color in python pygame

Now, we will see how to change the screen background color in python pygame.

  • Firstly, we will import pygame. The pygame.init() is used to initialize all the required modules of the pygame.
  • pygame.display.set_mode((500,400)) is used to initialize a screen for display.
  • Initially, the screen background color is set to color = (255,155, 0).
  • The fill(color) method is used to fill the display with the color specified.
  • pygame.display.flip() is used to update the content of the display to the screen.
  • To hold the screen we have used “while True: pass”.

Example:

import pygame
pygame.init() 
bg = pygame.display.set_mode((500,400)) 
color = (255,155, 0)
bg.fill(color) 
pygame.display.flip()
while True:
  pass

In this output, we can see that the new window appears, and the screen background color in pygame window.

How to change the screen background color in python pygame
How to change the screen background color in python pygame

To change the background color of the screen to other colors just change the value ranging from 0 to 255. We have to make a change in color using color = (255,255,0). In this way, my screen color is changed. You can refer to the below screenshot.

How to change the screen background color in python pygame
How to change the screen background color in python pygame

How to terminate game in python pygame

Lets see how to terminate game in python pygame

  • The pygame.quit() and sys.exit() function are called. The program should always call pygame.quit() before they call sys.exit() to terminate the program in python pygame.
  • Normally, it does not really matter since python closes it when the program exits anyway. But there is a bug in IDLE that causes IDLE to hang if a pygame program terminates before pygame.quit() is called.

Example:

import pygame, sys
from pygame.locals import *
pygame.init()
win = pygame.display.set_mode((500, 400))
pygame.display.set_caption('Pygame')
while True: 
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()
    pygame.display.update()

In this output, we can see that the new window appears, and the termination is done in the python pygame window.

How to terminate game in python pygame
How to terminate game in python pygame

How to add color breezing effect in python pygame

  • As we know pygame contains color coding, the three colors i.e, red, blue, green. The value of the individual colors can be changed in order to make a unique color.
  • Firstly, we will import pygame, random, and sys module. The pygame.init() is used to initialize all the required modules of the pygame.
  • We have taken three variable of the color which is a1, a2 and a3.
  • Now, we will set up a variable clock() as “clock = pygame.time.Clock()”.
  • To increase the shade of the current color we have given the if condition. If the value of a1 exceeds 255 it is reset to 0 and if the value of a1 precedes 0 then it is incremented by 3.
  • Let’s set the game fps to 60.
  • scr.fill((a1,a2,a3)) sets the background color tuple.

Example:

import pygame
import random
import sys
pygame.init()
scr = pygame.display.set_mode((700,650))
a1 = random.randint(0,255)
a2 = random.randint(0,255)
a3 = random.randint(0,255)
clock = pygame.time.Clock()
while True:
    for e in pygame.event.get():
        if e.type == pygame.QUIT:
            pygame.quit()
    if 0 < a1 < 255:
        a1 += 1
    elif a1 >= 255:
        a1 -= 255
    elif a1 <= 0:
        a1 += 3
    clock.tick(60)
    scr.fill((a1,a2,a3))
    pygame.display.update()

In this output, we can see that the new window appears, and the color breezing effect is added in python pygame

How to add color breezing effect in python pygame
How to add color breezing effect in python pygame
How to add color breezing effect in python pygame
How to add color breezing effect in python pygame

How to track mouse movement in python pygame

Now, we see how to track mouse movement in python

  • In the below code we have the x and y coordinates of the image. Set the x and y position of the mouse click.
  • The “image.get_rect().collidepoint(x, y):” is used to see if the mouse click event is fired and then we get the current visibility state of the mouse cursor.
  • So, we can see that the display is receiving mouse input when we click on the image.

Example:

import pygame
pygame.init()
w=550;
h=400
scr = pygame.display.set_mode( (w, h) )
pygame.display.set_caption('click on image')
image = pygame.image.load("img.jpg").convert()
x = 20;
y = 30; 
scr.blit(image, (x,y))
pygame.display.flip()
running = True
while (running):
    for e in pygame.event.get():
        if e.type == pygame.QUIT:
            running = False
        if e.type == pygame.MOUSEBUTTONDOWN:
            x, y = e.pos
            if image.get_rect().collidepoint(x, y):
                print('clicked on image')
pygame.quit()

In this output, we can see that the new window appears, and we have tracked mouse movement in python pygame. You can refer to the below screenshot.

How to track mouse movement in python pygame
How to track mouse movement in python pygame

How to create buttons in python pygame

Lets see how we can create button in python pygame.

  • To create a button first, we have to import pygame and sys module. The pygame.init() is used to initialize all the required modules of the pygame.
  • We have created three variables for color i.e color_white, color_light, and color_dark.
  • Now, we will store the width and height of the screen into a variable.
  • pygame.font.SysFont(‘Arial’,30) is used for defining the font type and its size.
  • Now, to render text written in this font we will use smallfont.render(‘Quit’ , True , color_white).
  • he pygame.MOUSEBUTTONDOWN check if the mouse is clicked.
  • if width/2 <= mouse[0] <= width/2+140 and height/2 <= mouse[1] <= height/2+40 this line check if the mouse is clicked on the button then the it will get terminated.
  • The screen.fill((0,0,0)) fills the screen with black color.
  • if width/2 <= mouse[0] <= width/2+140 and height/2 <= mouse[1] <= height/2+40 this is use to check if the mouse is hovered on the button it changes to lighter shades, and the else condition is used for darker color.
  • screen.blit(text , (width/2+50,height/2)) is superimposing the text onto our button.

Example:

import pygame 
import sys  
pygame.init() 
s = (600, 500)
screen = pygame.display.set_mode(s)
color_white = (255,255,255) 
color_light = (180,180,180) 
color_dark = (110,110,110) 
width = screen.get_width()
height = screen.get_height()  
smallfont = pygame.font.SysFont('Arial',30) 
text = smallfont.render('Quit' , True , color_white) 
while True:     
    for e in pygame.event.get():      
        if e.type == pygame.QUIT: 
            pygame.quit()      
        if e.type == pygame.MOUSEBUTTONDOWN: 
            if width/2 <= mouse[0] <= width/2+140 and height/2 <= mouse[1] <= height/2+40: 
                pygame.quit() 
    screen.fill((0,0,0)) 
    mouse = pygame.mouse.get_pos() 
    if width/2 <= mouse[0] <= width/2+140 and height/2 <= mouse[1] <= height/2+40: 
        pygame.draw.rect(screen,color_light,[width/2,height/2,140,40]) 
    else: 
        pygame.draw.rect(screen,color_dark,[width/2,height/2,140,40]) 
    screen.blit(text , (width/2+50,height/2)) 
    pygame.display.update() 

In this output, we can see that the new window appears, and the button is created in python pygame. You can refer to the below screenshot.

How to create buttons in python pygame
How to create buttons in python pygame

How to play audio in python with pygame

  • To play audio/music files in pygame, we will use pygame. mixer. The module contains classes for loading audio objects and controlling playback.
  • Firstly we will start the mixer and then we have to load the song you want to use.
  • Then we will set the volume using mixer.music.set_volume(0.5). The mixer.music.play() will start playing the song.
  • The infinite loop is used. If you want to pause the music then you can enter “p”. If you enter “r” the audio will resume and if you enter “e” then the audio will be stoped.

Example:

from pygame import mixer  
mixer.init() 
mixer.music.load("Curt Cool - Toi-Tei.ogg") 
mixer.music.set_volume(0.5) 
mixer.music.play() 
while True: 
    print("Press 'p' to pause, 'r' to resume") 
    print("Press 'e' to end the program") 
    enter = input("  ") 
    if enter == 'p': 
        mixer.music.pause()      
    elif enter == 'r': 
        mixer.music.unpause() 
    elif enter == 'e': 
        mixer.music.stop() 
        break

In this output, the audio is played, and below is the entered option to stop, resume, and pause the audio in python pygame. You can refer to the below screenshot.

How to play audio in python with pygame
How to play audio in python with pygame

How to display message on screen on two lines python pygame

  • Firstly, we have to import pygame. The pygame.init() is used to initialize all the required modules of the pygame.
  • To display the message on screen on two lines, we have to calculate it.
  • space = font.size(‘ ‘)[0] is the width of a space.
  • Now, render each word and check how many words can fit the screen by using the surface.get_width().
  • Also, blit the rest on another row which will be surface.get_height().
  • x = pos[0] is used to reset the x. The y += word_height is used to start on a new row.
  • text =”Welcome to python tutorial.\nHere you will learn about pygame” this will be written on the screen in two lines.

Example:

import pygame
pygame.init()
Size = WIDTH, HEIGHT = (900, 700)
FPS = 30
scr = pygame.display.set_mode(Size, pygame.RESIZABLE)
clock = pygame.time.Clock()
def blit_text(surface, text, pos, font, color=pygame.Color('blue')):
    words = [word.split(' ') for word in text.splitlines()]
    space = font.size(' ')[0]
    max_width, max_height = surface.get_size()
    x, y = pos
    for line in words:
        for word in line:
            word_surface = font.render(word, 0, color)
            word_width, word_height = word_surface.get_size()
            if x + word_width >= max_width:
                x = pos[0] 
                y += word_height
            surface.blit(word_surface, (x, y))
            x += word_width + space
        x = pos[0]
        y += word_height
text ="Welcome to python tutorial.\nHere you will learn about pygame"
font = pygame.font.SysFont('Arial', 70)
while True:
    dt = clock.tick(FPS) / 1000
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            quit()
    scr.fill(pygame.Color('black'))
    blit_text(scr, text, (20, 20), font)
    pygame.display.update()

In this output, we can see that the new window appears, and the message is displayed on two lines in the screen pygame window.

How to display message on screen on two lines python pygame
How to display message on screen on two lines python pygame

Python pygame animation

  • Firstly, we have to import pygame and sys module. The pygame.init() is used to initialize all the required modules of the pygame.
  • The FPS = 20 is used for frames per second setting.
  • To set the window we will use Displaysrf = pygame.display.set_mode((700, 600), 0, 20) and pygame.display.set_caption(‘Animation’) to set the name of the screen.
  • To load the image we will use “dImg = pygame.image.load(‘walk1.png’)”.
  • while True the main loop starts and the direction is set to make the image walk.
  • fpsClock.tick(FPS) set up how fast the game should run.

Example:

import pygame, sys
from pygame.locals import *
pygame.init()
FPS = 20
fpsClock = pygame.time.Clock()
Displaysrf = pygame.display.set_mode((700, 600), 0, 20)
pygame.display.set_caption('Animation')
white = (255, 255, 255)
dImg = pygame.image.load('walk1.png')
dx = 10
dy = 10
direction = 'right'
while True:
    Displaysrf.fill(white)
    if direction == 'right':
        dx += 5
        if dx == 280:
            direction = 'down'
    elif direction == 'down':
        dy += 5
        if dy == 220:
            direction = 'left'
    elif direction == 'left':
        dx -= 5
        if dx == 10:
            direction = 'up'
    elif direction == 'up':
        dy -= 5
        if dy == 10:
            direction = 'right'
    Displaysrf.blit(dImg, (dx, dy))
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()
    pygame.display.update()
    fpsClock.tick(FPS)

In this output, we can see that the new window appears, and the animation is displayed on the screen of pygame window.

Python pygame animation
Python pygame animation
Python pygame animation
Python pygame animation

Python pygame snow animation

Let see how snow animation in python pygame works

  • Firstly, we have to import pygame and random modules. The pygame.init() is used to initialize all the required modules of the pygame.
  • Now, set the height and width of the screen using size = [600, 400].
  • Created an empty array called snow_list = []
  • Here, the loop is used 50 times, and add snow in a random x,y position.
  • Loop until the user clicks the close button.
  • Set the screen background-color by using scr.fill(black).
  • Process each snowflakes in the list by using pygame.draw.circle(scr, white, snow_list[i], 2).
  • To move the snowflakes down one pixel use snow_list[i][1] += 1.
  • If the snowflakes have moved off the bottom of the screen then reset it just above the top.
  • Give it a new x position x = random.randrange(0, 400) and then go ahead to update the screen with what we have drawn.

Example:

import pygame
import random
pygame.init()
black = [0, 0, 0]
white = [255, 255, 255]
size = [600, 400]
scr = pygame.display.set_mode(size)
pygame.display.set_caption("Snow Animation")
snow_list = []
for i in range(50):
    x = random.randrange(0, 700)
    y = random.randrange(0, 600)
    snow_list.append([x, y])
clock = pygame.time.Clock()
done = False
while not done:
    for event in pygame.event.get(): 
        if event.type == pygame.QUIT:  
            done = True  
    scr.fill(black)
    for i in range(len(snow_list)):
        pygame.draw.circle(scr, white, snow_list[i], 2)
        snow_list[i][1] += 1
        if snow_list[i][1] > 400:
            y = random.randrange(-50, -10)
            snow_list[i][1] = y
            x = random.randrange(0, 400)
            snow_list[i][0] = x
    pygame.display.flip()
    clock.tick(20)
pygame.quit()

In this output, we can see that the new window appears, and the snow animation is displayed on the screen.

Python pygame snow animation
Python pygame snow animation

Python pygame animation with a circle

  • Firstly, we have to import pygame and sys modules. The pygame.init() is used to initialize all the required modules of the pygame.
  • After that color is defined as black and green. And the FPS = 50 is used for frames per second setting.
  • Now, we will set the position of a board and the velocity is set,
  • Now, to draw a circle we will use pygame.draw.circle(Display,Green, (x_Pos, y_Pos), 10, 0)
  • fpsClock.tick(FPS) set up how fast the game should run.

Example:

import pygame
import sys
from pygame.locals import *
Green = (0, 255, 0)
Black = (0, 0, 0)
FPS = 50
fpsClock = pygame.time.Clock()
x_Pos = 300
y_Pos = 250
x_Vel = -5
y_Vel = 5
pygame.init()
Display= pygame.display.set_mode((500, 400))
pygame.display.set_caption('Animation')
while True:
    Display.fill(Black)
    pygame.draw.circle(Display,Green, (x_Pos, y_Pos), 10, 0)
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()
    x_Pos += x_Vel
    y_Pos += y_Vel
    if x_Pos > 490 or x_Pos <10:
        x_Vel *= -1
    if y_Pos >390 or y_Pos <10:
        y_Vel *= -1
    pygame.display.update()
    fpsClock.tick(FPS)

In this output, we can see that the new window appears, and the animation with a circle is displayed on the screen.

Python pygame animation with a circle
Python pygame animation with a circle
Python pygame animation with a circle
Python pygame animation with a circle

Python how to get user input in a pygame window

Lets see how to get user input in a pygame window.

  • Firstly, we have to import pygame and sys modules. The pygame.init() is used to initialize all the required modules of the pygame.
  • pygame.display.set_mode([500,500]) is used to initialize a screen for display.
  • pygame.font.Font(None,32) is used for text font which is default and the size of the text is 32.
  • The user_text is empty now we will use this to add information into it.
  • if event.type == pygame.KEYDOWN check if any button is pressed.
  • event.unicode checks which specific button was pressed.
  • if event.key == pygame.K_BACKSPACE is used to check if the backspace key is pressed.
  • user_text[:-1] is used for getting the first character to one before last.
  • pygame.draw.rect(scr,color,input_rect,2) is used for drawing rectangle on the screen.
  • Now, we create a variable text_surface = base_font.render(user_text,True,(255,255,255)) and the text will be render on the surface.

Example:

import pygame,sys
pygame.init()
clock = pygame.time.Clock()
scr = pygame.display.set_mode([500,500])
base_font = pygame.font.Font(None,32)
user_text = ""
input_rect = pygame.Rect(200,200,140,32)
color_active = pygame.Color("Green")
color_passive = pygame.Color("yellow")
color = color_passive
active = False
while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
        if event.type == pygame.MOUSEBUTTONDOWN:
            if input_rect.collidepoint(event.pos):
                active = True
            else:
                active = False
        if event.type == pygame.KEYDOWN:
            if active == True:
                if event.key == pygame.K_BACKSPACE:
                    user_text = user_text[:-1]
                else:
                    user_text += event.unicode
    scr.fill((0,0,0))
    if active:
        color = color_active
    else:
        color = color_passive
    pygame.draw.rect(scr,color,input_rect,2)
    text_surface = base_font.render(user_text,True,(255,255,255))
    scr.blit(text_surface,(input_rect.x + 5,input_rect.y + 5))
    input_rect.w = max(100,text_surface.get_width() + 10)
    pygame.display.flip()
    clock.tick(50)

In this output, we can see that the new window appears, and the user input is entered on a pygame window.

Python how to get user input in a pygame window
Python how to get user input in a pygame window

Python pygame animate a ball to move in a sine pattern

  • Firstly, we have to import pygame. The pygame.init() is used to initialize all the required modules of the pygame.
  • pygame.display.set_mode((500,500)) is used to initialize a screen for display.
  • pygame.time.get_ticks() / 2 % 400 this will return how many milliseconds since pygame.init() was called. Then, divide by 2 is used to slow it down, and % 400 will make it loop between 0-400.
  • To draw a circle we have used pygame.draw.circle(scr, (255,255,255), (x, y), 30).

Example:

import math
import pygame
pygame.init()
scr = pygame.display.set_mode((500,500))
while True:
    t = pygame.time.get_ticks() / 2  % 400
    x = t
    y = math.sin(t/50.0) * 100 + 200       
    y = int(y)                            
    scr.fill((0,0,0))
    pygame.draw.circle(scr, (255,255,255), (x, y), 30)
    pygame.display.flip()

In this output, we can see that the new window appears, and the sine pattern is formed while the balls move in the pygame window.

Python pygame animate a ball to move in a sin pattern
Python pygame animate a ball to move in a sin pattern

You may like the following Python tutorials:

In this Python pygame tutorial, we have learned about Python Pygame and also we have covered these topics:

  • What is Pygame in python?
  • How to install Pygame in python
  • Pygame module in python
  • Python Pygame example
  • How to put the screen in a specific spot in python pygame
  • How to get the size of python pygame window
  • How to resize a window in python pygame
  • How to draw a circle using python pygame
  • How to draw a rectangle using python pygame
  • How to draw a line using python pygame
  • How to draw an ellipse using python pygame
  • How to draw a polygon using python pygame
  • How to draw a triangle using python pygame
  • How to draw an arc using python pygame
  • How to get the font in python using pygame
  • How to display text in python pygame
  • Python how to make a text rectangle in pygame
  • How to move an object in python pygame
  • Draw design using the arrow keys in python pygame
  • How to scale an image in python pygame
  • How to display an image in python pygame
  • Python pygame error: No such file or directory while displaying an image
  • Resize the image in python pygame
  • How to add background image in python pygame
  • How to add an image to a background image in python pygame
  • How to change the screen background color in python pygame
  • How to terminate game in python pygame
  • How to add color breezing effect in python pygame
  • How to track mouse movement in python pygame
  • How to create buttons in python pygame
  • How to play audio in python with pygame
  • How to display message on screen on two lines python pygame
  • Python pygame animation
  • Python pygame snow animation
  • Python pygame animation with a circle
  • Python how to get user input in a pygame window
  • Python pygame animate a ball to move in a sine pattern