-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinputbox.py
59 lines (47 loc) · 1.78 KB
/
inputbox.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
import pygame
pygame.init()
# Màu sắc
COLOR_INACTIVE = pygame.Color('lightskyblue3')
COLOR_ACTIVE = pygame.Color('dodgerblue2')
WHITE = pygame.Color('white')
BLACK = pygame.Color('black')
# Phông chữ
font_path = 'fonts/SVN-Determination Sans.otf'
font = pygame.font.Font(font_path, 15)
class InputBox():
def __init__(self, x, y, w, h, text='', placeholder='Nhập ...'):
self.rect = pygame.Rect(x, y, w, h)
self.color = COLOR_INACTIVE
self.text = text
self.placeholder = placeholder
self.txt_surface = font.render(self.text, True, WHITE)
self.active = False
def handle_event(self, event):
if event.type == pygame.MOUSEBUTTONDOWN:
if self.rect.collidepoint(event.pos):
self.active = not self.active
else:
self.active = False
self.color = COLOR_ACTIVE if self.active else COLOR_INACTIVE
if event.type == pygame.KEYDOWN:
if self.active:
if event.key == pygame.K_BACKSPACE:
self.text = self.text[:-1]
else:
self.text += event.unicode
self.txt_surface = font.render(self.text, True, WHITE)
def update(self):
width = max(200, self.txt_surface.get_width() + 10)
self.rect.w = width
def draw(self, screen):
if not self.text:
txt_surface = font.render(self.placeholder, True, WHITE)
else:
txt_surface = self.txt_surface
screen.blit(txt_surface, (self.rect.x + 5, self.rect.y + 5))
pygame.draw.rect(screen, self.color, self.rect, 2)
def get_text(self):
return self.text
def clear_text(self):
self.text = ''
self.txt_surface = font.render(self.text, True, BLACK)