From b01eaafdc47abee3162f385495978d95a373b68d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Czeka=C5=84ski?= Date: Sat, 4 Apr 2020 18:26:19 +0200 Subject: [PATCH] Add invoking functions when UiButton click --- src/ui/UiButton.py | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/src/ui/UiButton.py b/src/ui/UiButton.py index 66c7860..00f91ff 100644 --- a/src/ui/UiButton.py +++ b/src/ui/UiButton.py @@ -1,5 +1,4 @@ from enum import Enum - import pygame from src.ui.UiElement import UiElement @@ -8,7 +7,10 @@ from src.ui.UiElement import UiElement class UiButton(UiElement): def __init__(self, rect: pygame.Rect, notClickedBtnColor=(125, 125, 125), clickedBtnColor=(255, 255, 255), - text="Click", textColor=(0, 0, 0), font=None): + text="Click", textColor=(0, 0, 0), font=None, functionsToInvokeWhenClicked=[]): + """ + :type functionsToInvokeWhenClicked : list of tuple(function, args*), args are function arguments + """ super().__init__(rect) if font is None: self.font = pygame.font.Font(None, 25) @@ -21,6 +23,8 @@ class UiButton(UiElement): self.beingClicked = False self.image = self._images[0] + self.functionsToInvokeWhenClicked = functionsToInvokeWhenClicked + def eventHandler(self, event): # change selected color if rectangle clicked if event.type == pygame.MOUSEBUTTONDOWN: @@ -28,6 +32,8 @@ class UiButton(UiElement): if self.rect.collidepoint(event.pos): # is mouse over button self.image = self._images[ButtonImages.CLICKING_IMAGE.value] self.beingClicked = True + for func, *args in self.functionsToInvokeWhenClicked: + func(*args) elif event.type == pygame.MOUSEBUTTONUP and self.beingClicked: if event.button == 1: self.beingClicked = False @@ -46,6 +52,12 @@ class UiButton(UiElement): self._images[0].blit(self.textSurface, self.textSurfaceDest) self._images[1].blit(self.textSurface, self.textSurfaceDest) + def addFuncToInvoke(self, tupleOfFuncAndArgs): + """ + :type tupleOfFuncAndArgs: tuple(function, *args) + """ + self.functionsToInvokeWhenClicked.append(tupleOfFuncAndArgs) + class ButtonImages(Enum): DEFAULT_IMAGE = 0