container.py 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. # -*- coding: utf-8 -*-
  2. import pygame
  3. from .widget import Widget
  4. class Container(Widget):
  5. def __init__(self, x, y, width=10, height=10, bg_color=None):
  6. super().__init__(x=x, y=y, width=width, height=height, bg_color=bg_color)
  7. self._Canvas = pygame.Surface((self._Width, self._Height), pygame.SRCALPHA, 32)
  8. # noinspection PyArgumentList
  9. self._Canvas.convert_alpha()
  10. self._Childs = []
  11. def add_child(self, child: Widget):
  12. self._Childs.append(child)
  13. child.set_parent(self)
  14. def set_size(self, width, height):
  15. super().set_size(width, height)
  16. # Recreate the surface
  17. self._Canvas = pygame.Surface((self._Width, self._Height), pygame.SRCALPHA, 32)
  18. # noinspection PyArgumentList
  19. self._Canvas.convert_alpha()
  20. def Draw(self):
  21. if self._BG_Color is not None:
  22. pygame.draw.rect(self._Canvas, self._BG_Color, (0, 0, self._Width, self._Height))
  23. for c in self._Childs:
  24. c.Draw()
  25. if self._Parent is not None:
  26. self._Parent.get_canvas().blit(self._Canvas, self._Rect)
  27. def handle_event(self, evt):
  28. super().handle_event(evt)
  29. for c in self._Childs:
  30. c.handle_event(evt)