I have the following code below that is a class for a button taken from another post. I was wondering if I can change the opacity of the background of the button without changing the opacity of the text on it. How can I achieve this?
Code:
import pygame
pygame.init()
font = pygame.font.SysFont('Microsoft New Tai Lue', 23)
class Button(pygame.sprite.Sprite):
# 1) no need to have 4 parameters for position and size, use pygame.Rect instead
# 2) let the Button itself handle which color it is
# 3) give a callback function to the button so it can handle the click itself
def __init__(self, color, color_hover, rect, callback, text='', outline=None):
super().__init__()
self.text = text
# a temporary Rect to store the size of the button
tmp_rect = pygame.Rect(0, 0, *rect.size)
self.org = self._create_image(color, outline, text, tmp_rect)
self.hov = self._create_image(color_hover, outline, text, tmp_rect)
self.image = self.org
self.rect = rect
self.callback = callback
def _create_image(self, color, outline, text, rect):
img = pygame.Surface(rect.size)
#img.set_alpha(110)
if outline:
img.fill(outline)
img.fill(color, rect.inflate(-4, -4))
else:
img.fill(color)
# render the text once here instead of every frame
if text != '':
text_surf = font.render(text, 1, pygame.Color('white'))
text_rect = text_surf.get_rect(center=rect.center)
img.blit(text_surf, text_rect)
return img
def update(self, events):
# here we handle all the logic of the Button
pos = pygame.mouse.get_pos()
hit = self.rect.collidepoint(pos)
self.image = self.hov if hit else self.org
for event in events:
if event.type == pygame.MOUSEBUTTONDOWN and hit:
self.callback(self)
Any help is appreciated.