You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

73 lines
2.1 KiB

"""
Module which add an interactive textbox into pygame
"""
# false positive
# pylint: disable=no-member
import pygame as pg
COLOR_INACTIVE = pg.Color('lightskyblue3')
COLOR_ACTIVE = pg.Color('dodgerblue2')
FONT = pg.font.Font(None, 32)
class InputBox:
"""
Box for data input
"""
def __init__(self, rect, text=''):
self.rect = pg.Rect(rect)
self.color = COLOR_INACTIVE
self.text = text
self.txt_surface = FONT.render(text, True, self.color)
self.active = False
def handle_event(self, event):
"""
handles the button click event
"""
if event.type == pg.MOUSEBUTTONDOWN:
# If the user clicked on the input_box rect.
if self.rect.collidepoint(event.pos):
# Toggle the active variable.
self.active = not self.active
else:
self.active = False
# Change the current color of the input box.
self.color = COLOR_ACTIVE if self.active else COLOR_INACTIVE
if event.type == pg.KEYDOWN:
if self.active:
if event.key == pg.K_RETURN:
print(self.text)
self.text = ''
elif event.key == pg.K_BACKSPACE:
self.text = self.text[:-1]
else:
if str(event.unicode).isnumeric():
self.text += event.unicode
# Re-render the text.
self.txt_surface = FONT.render(self.text, True, self.color)
def update(self):
"""
Resize the box if the text is too long.
"""
width = max(200, self.txt_surface.get_width()+10)
self.rect.w = width
def draw(self, screen):
"""
Draws the button on the screen
"""
screen.blit(self.txt_surface, (self.rect.x+5, self.rect.y+5))
pg.draw.rect(screen, self.color, self.rect, 2)
def value(self):
"""
Returns a numerical value of the box
"""
if self.text == '':
return 0
return int(self.text)

Powered by TurnKey Linux.