开发者

Pygtk entry placeholder

How to create p开发者_JAVA技巧ygtk entry with placeholder like in HTML 5 input element?


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()


Since version 3.2, Gtk+ supports GtkEntry placeholder, but the only way to take advantage of it with Python is by using PyGobject instead of PyGtk.

Regards


You can use PyGobject instead of pygtk, and then setting a placeholder is a piece of cake: entry.set_placeholder_text("some string")

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜