How to Draw Rectangles in Pygame

In this Pygame article we want to learn How to Draw Rectangles in Pygame, if you are creating a game or any other kind of interactive program with Pygame, some times you will need to draw rectangles. Rectangles are useful for creating game objects, UI elements and much more. in this article we want to talk that how to draw rectangles using pygame.draw.rect() function.


First if all you need to import Pygame module and initialize it with pygame.init() function.



So before you draw a rectangle, you need to set dimensions of the Pygame display. you can do this using pygame.display.set_mode() function.



Now we are ready to draw rectangle, pygame.draw.rect() function takes several arguments, including display surface to draw on, color of the rectangle, position of the top left corner of rectangle and  dimensions of the rectangle. this is an example of how to draw a rectangle:



After drawing a rectangle, you need to update Pygame display for the changes to take effect. you can do this with pygame.display.update() function.



This is the complete code for this article

This code initializes Pygame and sets dimensions of the display window. after that it draws  red rectangle using pygame.draw.rect(). and finally this code enters a game loop that continually updates the display until the user closes the window.



Run the complete code and this will be the result

How to Draw Rectangles in Pygame
How to Draw Rectangles in Pygame




Learn More on Pygame



So we can say that Drawing rectangles is an important part of creating games and interactive programs. by using pygame.draw.rect() function you can easily draw rectangles of any size and color. just remember to update the display for the changes to take effect.

Leave a Comment