Skip to main content
Engineering LibreTexts

3.12: pygame.Color Objects

  • Page ID
  • You need to know how to represent a color because Pygame’s drawing functions need a way to know what color you want to draw with. A tuple of three or four integers is one way. Another way is as a pygame.Color object. You can create Color objects by calling the pygame.Color() constructor function and passing either three or four integers. You can store this Color object in variables just like you can store tuples in variables. Try typing the following into the interactive shell:

    >>> import pygame
    >>> pygame.Color(255, 0, 0)
    (255, 0, 0, 255)
    >>> myColor = pygame.Color(255, 0, 0, 128)
    >>> myColor == (255, 0, 0, 128)

    Any drawing function in Pygame (which we will learn about in a bit) that has a parameter for color can have either the tuple form or Color object form of a color passed for it. Even though they are different data types, a Color object is equal to a tuple of four integers if they both represent the same color (just like how 42 == 42.0 will evaluate to True).

    Now that you know how to represent colors (as a pygame.Color object or a tuple of three or four integers for red, green, blue, and optionally alpha) and coordinates (as a tuple of two integers for X and Y), let’s learn about pygame.Rect objects so we can start using Pygame’s drawing functions.