Add enable / disabled toggle to TextButton
authorNeil <neil@dip.sun.ac.za>
Sat, 10 Sep 2016 20:31:02 +0000 (22:31 +0200)
committerNeil <neil@dip.sun.ac.za>
Sat, 10 Sep 2016 20:36:33 +0000 (22:36 +0200)
tabakrolletjie/widgets.py

index 156cb6cbab8491d8233f289fb2d8401f04128cfa..c1bbc941c38a924153af2875e9af59449b1b776f 100644 (file)
@@ -6,7 +6,7 @@ import pygame.locals as pgl
 
 from .loader import loader
 from .constants import FONTS
-from .transforms import NullTransform
+from .transforms import NullTransform, Multiply
 
 
 class Button(object):
@@ -16,6 +16,13 @@ class Button(object):
         self._padding = padding
         self.position = pos
         self.name = name
+        self.enabled = True
+
+    def enable(self):
+        self.enabled = True
+
+    def disable(self):
+        self.enabled = False
 
     @property
     def position(self):
@@ -40,6 +47,8 @@ class Button(object):
         pass
 
     def pressed(self, ev):
+        if not self.enabled:
+            return False
         if self._pos is None:
             # Unplaced buttons can't be pressed
             return False
@@ -63,11 +72,16 @@ class TextButton(Button):
     def __init__(self, text, colour, name=None, pos=None, padding=10):
         font = loader.load_font(FONTS['sans'], size=24)
         self._text = font.render(text, True, colour)
+        self._disabled_text = self._text.copy()
+        Multiply(colour=(80, 80, 80)).apply(self._disabled_text)
         super(TextButton, self).__init__(self._text.get_size(), name,
                                          pos, padding)
 
     def render(self, surface):
-        surface.blit(self._text, self._pos, None)
+        if self.enabled:
+            surface.blit(self._text, self._pos, None)
+        else:
+            surface.blit(self._disabled_text, self._pos, None)
 
 
 class ImageButton(Button):
@@ -86,6 +100,7 @@ class ImageButton(Button):
     def update_image(self, *imgparts, **kwargs):
         transform = kwargs.pop("transform", NullTransform())
         self._img = loader.load_image(*imgparts, transform=transform)
+        Multiply((128, 128, 128)).apply(self._disabled_img)
 
     def render(self, surface):
         surface.blit(self._img, self._pos, None)