Simple Python Text-Entry

Posted on Sun 04 October 2015 in Projects

image0

Recently for my biogen project I needed a way to create pop-up text entries for users using virtualenv. Sadly, neither wxPython nor TkInter would work easily without ugly hacks involving symlinking to system directories. Eventually I worked out that Gtk would work via pip. However, I couldn't find sample code anywhere that ran synchronously(not via signals), so I could wait to grab the users input before proceeding along execution. So I cooked up some sample code that might help others.

from pgi.repository import Gtk, GObject

class EntryWindow(Gtk.Window):

    def __init__(self, ask_title="Title", ask_body="Body", message="Message"):
        Gtk.Window.__init__(self, title=ask_title)
        self.set_size_request(200, 100)

        self.timeout_id = None

        vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=6)
        self.add(vbox)

        label = Gtk.Label(message)
        vbox.pack_start(label, True, True, 0)

        self.entry = Gtk.Entry()
        self.entry.set_text(ask_body)
        vbox.pack_start(self.entry, True, True, 0)

        hbox = Gtk.Box(spacing=6)
        vbox.pack_start(hbox, True, True, 0)

        button = Gtk.Button(label="OK")
        button.connect("clicked",self.on_ok_button_clicked)
        vbox.pack_start(button, True, True, 0)

    def on_ok_button_clicked(self,button):
        Gtk.main_quit()

    def run(self):
        self.show_all()
        Gtk.main()
        result = self.entry.get_text()
        self.destroy()
        return result

The import uses pgi.repositories not gi.repositories as I needed it to be compatible with PyPy for speed.

To then run this code(and grab it's input), use something like this.

win = EntryWindow("My Title", "Enter Some Text", "Some message")
response_text = win.run()