tags:

views:

92

answers:

1

How to create pygtk entry with placeholder like in HTML 5 input element?

+5  A: 

Try this code if it does what you need:

import gtk


class PlaceholderEntry(gtk.Entry):

    placeholder = 'Username'
    _default = True

    def __init__(self, *args, **kwds):
        gtk.Entry.__init__(self, *args, **kwds)
        self.connect('focus-in-event', self._focus_in_event)
        self.connect('focus-out-event', self._focus_out_event)

    def _focus_in_event(self, widget, event):
        if self._default:
            self.set_text('')
            self.modify_text(gtk.STATE_NORMAL, gtk.gdk.color_parse('black'))

    def _focus_out_event(self, widget, event):
        if gtk.Entry.get_text(self) == '':
            self.set_text(self.placeholder)
            self.modify_text(gtk.STATE_NORMAL, gtk.gdk.color_parse('gray'))
            self._default = True
        else:
            self._default = False

    def get_text(self):
        if self._default:
            return ''
        return gtk.Entry.get_text(self)


if __name__ == '__main__':
    w = gtk.Window()
    vbox = gtk.VBox()
    w.add(vbox)
    vbox.pack_start(PlaceholderEntry())
    quitbtn = gtk.Button(stock=gtk.STOCK_QUIT)
    quitbtn.connect('clicked', gtk.main_quit)
    vbox.pack_start(quitbtn)
    w.connect('destroy', gtk.main_quit)
    w.show_all()
    gtk.main()
mg