why must display be initialized when setting palette?

Viewed 53

I want to manually create and save a color-indexed image (palette) as a PNG file, using pygame :

# create the bitmap
res = pygame.Surface((src.width, src.height), depth=8)

# create the palette
res.set_palette([pygame.Color((0, 0, 0, 0)), ...])

pygame.image.save(res, "test.png")

But I get :

error: cannot set palette without pygame.display initialized

on the set_palette line.

Of course, it isn't difficult to initialize some dummy display, but I don't see why it should be the case. Nothing is displayed, and nothing seems display dependant in my code...

Also, it's totally useless to initialize pygame or display when you manipulate 32 bits Surfaces. What's the difference between them ?

2 Answers

The reason is because the pygame source says so :)

But I couldn’t find any reason it was necessary, so I recently removed that check in https://github.com/pygame/pygame/pull/3259.

So this will not be the case in the next pygame release.

Your code is wrong, because you create a surface no alpha channel (no SRCALPHA flag), but set an alpha channel with 0. Set a color without alpha channel:

res.set_palette([pygame.Color((0, 0, 0, 0)), ...])

res.set_palette([pygame.Color((0, 0, 0)), ...])

A pygame.Surface is somehow associated with the display and is created in a format that best suits the display surface. You need to initialize Pygame with pygame.init() or initialize at least the display module with pygame.display.init().

Minimal working example:

import pygame

pygame.display.init()
res = pygame.Surface((1, 1), depth=8)

# create the palette
res.set_palette([pygame.Color((0, 0, 0))])
Related