wobbl_tools/pygame_tools/widgets/text_button.py

65 lines
1.9 KiB
Python
Raw Normal View History

#!/usr/bin/python3
from wobbl_tools.pygame_tools.utils import *
from wobbl_tools.pygame_tools.widgets import Button
class TextButton(pygame.sprite.Sprite):
"""
Creates a button from just some string and a position.
"""
def __init__(
self,
text: str,
position: tuple,
function=None,
args: tuple=None,
key: int=0,
text_color: tuple=white,
bg_color: tuple=gray,
font: pygame.font.Font=default_font,
padding: tuple=(8, 8),
border_radius: int=0,
line_thickness: int = 0
):
pygame.sprite.Sprite.__init__(self)
self.text = text
self.position = position
self.text_color = text_color
self.font = font
self.function = function
self.args = args
self.key = key
self.bg_color = bg_color
self.padding = padding
self.border_radius = border_radius
self.line_thickness = line_thickness
self.image, self.size = self.generate_surface()
self.rect = self.make_rect()
self.button = Button(self.rect, self.function, args, self.key)
def generate_surface(self):
text_object = self.font.render(self.text, True, self.text_color)
w, h = text_object.get_size()
w, h = w + self.padding[0] * 2, h + self.padding[1] * 2
surface = pygame.Surface((w, h), pygame.SRCALPHA)
pygame.draw.rect(surface, self.bg_color, pygame.Rect((0, 0), (w, h)), self.line_thickness, self.border_radius)
surface.blit(text_object, (self.padding[0], self.padding[1]))
return surface, (w, h)
def make_rect(self):
return pygame.Rect(self.position, self.size)
def draw(self, surface: pygame.Surface):
surface.blit(self.image, self.position)
def check(self, mouse_pos, pressed):
return self.button.check(mouse_pos, pressed)