Search code examples
python-3.ximagepygameiconstransparency

icon in pygame does not load transparency correctly


I have looked over every other question related to mine and none of them worked, here is my code so far:

icon = pygame.image.load('icon.png')
surface= pygame.Surface(icon.get_size(), depth=24)
key = (0,255,0)
surface.fill(key, surface.get_rect())
surface.set_colorkey(key)
surface.blit(icon, (0,0))
surface.set_alpha(128) 

pygame.display.set_icon(surface)

The original image is:

but when executed it still contains a black background, with a barely visable 'P'

Note: sorry for really big image not sure how to scale it down


Solution

  • Change your code to

    icon = pygame.image.load('icon.png')
    icon = pygame.transform.scale(icon, (32, 32))
    surface= pygame.Surface(icon.get_size())
    key = (0,255,0)
    surface.fill(key)
    surface.set_colorkey(key)
    surface.blit(icon, (0,0))
    
    pygame.display.set_icon(surface)
    

    Note the changes:

    I removed surface.set_alpha(128) since it will not work. Only a colorkey is supported for icons, but not per-pixel alpha.

    I changed surface.fill(key, surface.get_rect()) to surface.fill(key) because passing surface.get_rect() as argument is unnecessary.

    Also, the line icon = pygame.transform.scale(icon, (32, 32)) was added to ensure the image has the right size. Bigger sizes often do not work (depending on your OS/window manager).