Mercurial > mamba
view mamba/widgets/entrybox.py @ 245:0975a995113b
Factor out entry widget a bit
author | Neil Muller <drnlmuller@gmail.com> |
---|---|
date | Thu, 15 Sep 2011 00:20:02 +0200 |
parents | 5b021e8498b3 |
children | feca52afc109 |
line wrap: on
line source
import pygame from pygame.constants import SRCALPHA, K_ESCAPE, K_RETURN, K_UP, K_DOWN from mamba.widgets.base import Container from mamba.constants import DELETE_KEYS from mamba.widgets.text import TextWidget, TextButton, EntryTextWidget class EntryBox(Container): def __init__(self, rect, text, init_value, accept_callback=None, color='white', entry_color='yellow'): super(EntryBox, self).__init__(rect) self.text = text self.accept_callback = accept_callback self.color = color self.entry_color = entry_color self.value = init_value self.prepare() self.modal = True def prepare(self): message = TextWidget((self.rect.left + 50, self.rect.top + 2), self.text, color=self.color) self.rect.width = message.rect.width + 100 self.add(message) self.entry_text = EntryTextWidget((self.rect.left + 5, self.rect.top + message.rect.height + 5), self.value, update=self.edit, focus_color=self.entry_color) self.add(self.entry_text) ok_button = TextButton((self.rect.left + 50, self.entry_text.rect.bottom), 'Accept') ok_button.add_callback('clicked', self.close, True) self.add(ok_button) cancel_button = ok_button = TextButton( (self.entry_text.rect.right + 60, self.entry_text.rect.bottom), 'Cancel') cancel_button.add_callback('clicked', self.close, False) self.add(cancel_button) def draw(self, surface): background = pygame.Surface(self.rect.size, SRCALPHA) background.fill(pygame.Color('gray')) surface.blit(background, self.rect) super(EntryBox, self).draw(surface) def close(self, ev, widget, ok): if self.accept_callback and ok: if self.accept_callback(self.value): if self.parent: self.parent.remove(self) # Don't remove if the accept callback failed return self.parent.remove(self) def edit(self, ev, widget): if ev.key == K_ESCAPE: self.close(ev, widget, False) elif ev.key == K_RETURN: self.close(ev, widget, True) elif ev.key in DELETE_KEYS: if self.value: self.value = self.value[:-1] self.entry_text.update(self.value) elif ev.key in (K_UP, K_DOWN): return False # pass this up to parent else: self.value += ev.unicode self.entry_text.update(self.value) return True def grab_focus(self): self.entry_text.grab_focus()