A color in pygame is three numbers: how much red, green and blue light to mix, each from 0 (none) to 255 (full). (255, 0, 0) is red, (0, 0, 0) is black and (255, 255, 255) is white.
Every function that takes a color (fill, pygame.draw, font.render) accepts all of these forms.
Three ways to write a color
| Form | Example | Notes |
|---|---|---|
| RGB tuple | (255, 140, 0) | The usual form. Whole numbers from 0 to 255 |
| Name | "darkorange" | Not case sensitive. The list is pygame.color.THECOLORS |
| Hex string | "#ff8c00" | Like CSS. "#ff8c0080" adds alpha |
Some mixes worth knowing: equal red, green and blue is a gray ((128, 128, 128)); red plus green is yellow; red plus blue is purple; green plus blue is cyan.
Many games keep their colors as constants at the top of the file, so they are easy to change:
BACKGROUND = (24, 26, 40)
PLAYER = (255, 196, 0)
ENEMY = (230, 70, 70)
pygame.Color
pygame.Color is a color object. It takes any of the forms above and gives you its parts and some useful methods:
135 206 235
a.lerp(b, t) blends from a at t = 0 to b at t = 1, which draws the gradient above. A Color also has .a (alpha), .hsva for hue, saturation and value, and supports +, - and * per channel, clamped to 0 to 255.
Transparency (alpha)
A fourth number, alpha, sets how opaque a color is: 255 is solid, 0 is invisible. The screen itself has no transparency, so to see alpha work you draw on a Surface made with pygame.SRCALPHA and then blit it:
The white panel lets the circle show through. Pygame Surface covers SRCALPHA, set_alpha() and color keys in detail.
Invalid colors
A color pygame cannot read stops the program:
ValueError: invalid color (color sequence must have size 3 or 4, and each element must be an integer in the range [0, 255])
The usual causes are a tuple with two values, or a computed value that went over 255 or below 0, such as a color that fades a little every frame. Keep computed values in range with max(0, min(255, value)). A misspelled name gives ValueError: invalid color name.
Frequently Asked Questions
How do I write a color in pygame?
As a tuple of red, green and blue from 0 to 255, such as (255, 0, 0) for red; as a name, such as "red" or "skyblue"; or as a hex string, such as "#ff8800". Every pygame function that takes a color accepts all three.
What color names does pygame know?
Several hundred, from the X11 color list: "white", "black", "red", "gold", "tomato", "navy", "darkgreen" and many more. The full table is the dictionary pygame.color.THECOLORS.
What does ValueError: invalid color mean?
Pygame could not read the color: a tuple with the wrong number of values, a value outside 0 to 255, or a name it does not know. Check for typos, and keep computed values in range with max(0, min(255, value)).