Skip to content
Advertisement

Transparency problem displaying text with Pygame

enter image description hereI would like to display transparent text on a surface that is sized based on the length of the text. The problem is that the text has a black background even though “None” is specified as the background in the “render” command. I tried to apply the solutions given for questions similar to mine but they didn’t work. I attach the code and thank you for any suggestions.

import pygame
from pygame.locals import *

pygame.init()
screen = pygame.display.set_mode((800, 600))
screen.fill ((0,0,255))

# red square
surf1 = pygame.Surface((200, 200))
surf1.fill((255, 0, 0))
rect1 = surf1.get_rect()
rect1.topleft = (50, 50)
screen.blit(surf1, rect1)

# Play button
fnt = pygame.font.SysFont("Times New Roman", 27, bold=True)
btn_play = fnt.render("Play", True, (51, 26, 0), None)
btn_play_size = btn_play.get_size()
btn_play_surface = pygame.Surface(btn_play_size)
btn_play_surface.blit(btn_play, (0, 0))
rect_btn_play = pygame.Rect(380, 50, btn_play_size[0], btn_play_size[1])
screen.blit(btn_play_surface, (380, 50))
pygame.display.flip()

def events():
    done = False
    while not done:
        for ev in pygame.event.get():
            if ev.type == QUIT:
                return "quit"
            elif ev.type == MOUSEBUTTONDOWN:
                click = ev.pos
                if rect1.collidepoint(click):
                    return "Red squre"
                elif rect_btn_play.collidepoint(click):
                    return "Play"
                else:
                    print ("You clicked outside of the surfaces")

while True:
    event = events()
    print (event)
    if event == "quit":
        break
pygame.quit()

Advertisement

Answer

The problem is the surface you are placing the text on. If you want to keep the transparency in the formation of the text, you need to create a pygame.Surface object with an per pixel alpha format. Use the pygame.SRCALPHA flag:

btn_play_surface = pygame.Surface(btn_play_size)

btn_play_surface = pygame.Surface(btn_play_size, pygame.SRCALPHA)

Alternatively you can set the color key for the transparent color with set_colorkey:

btn_play_surface = pygame.Surface(btn_play_size)
btn_play_surface.set_colorkey((0, 0, 0))

enter image description here

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement