tuikit/button.py
author Radek Brich <radek.brich@devl.cz>
Tue, 04 Oct 2011 22:51:12 +0200
changeset 16 8791a7da6835
parent 13 19ebde2fd594
child 18 e6c3a5ee91aa
permissions -rw-r--r--
Update VerticalLayout/HorizontalLayout. Add layout demo. Add Size, Borders to common. Update Coords, Rect.

# -*- coding: utf-8 -*-

from .widget import Widget


class Button(Widget):
    
    '''Clickable button.'''
    
    def __init__(self, label=''):
        '''Create button with given label, size according to label.'''
        w = len(label) + 4
        h = 1
        Widget.__init__(self, w, h)

        #: Button label.
        self.label = label
        self.bg = 'button'
        self.bghi = 'button-active'
        self.highlight = False
        
        # size
        self.sizereq.w = w
        self.sizereq.h = h

        #: Left bracket graphic character.
        self.lbracket = '['
        #: Right bracket graphic character.
        self.rbracket = ']'

        self.connect('draw', self.on_draw)
        self.connect('mousedown', self.on_mousedown)
        self.connect('mouseup', self.on_mouseup)
        self.connect('keypress', self.on_keypress)

        self.addevents('click')


    def on_draw(self, screen, x, y):
        l = (self.width - len(self.label)) // 2
        screen.pushcolor(self.getcolor())
        screen.putch(x, y, self.lbracket)
        for i in range(x+1, x+l):
            screen.putch(i, y, ' ')
        screen.puts(x + l, y, self.label)
        for i in range(x+l+len(self.label), x+self.width-1):
            screen.putch(i, y, ' ')
        screen.putch(x + self.width - 1, y, self.rbracket)
        screen.popcolor()


    def on_mousedown(self, ev):
        self.highlight = True
        self.redraw()


    def on_mouseup(self, ev):
        self.highlight = False
        self.redraw()

        if self.enclose(ev.px, ev.py):
            self.handle('click')


    def on_keypress(self, keyname, char):
        if keyname == 'enter':
            self.handle('click')


    def getcolor(self):
        if self.highlight or self.hasfocus():
            return self.bghi
        return self.bg