Add invoking functions when UiButton click
This commit is contained in:
parent
6fc3a3155d
commit
b01eaafdc4
@ -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
|
||||
|
Loading…
Reference in New Issue
Block a user