Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect keypress when Gtk.Entry is in focus

I was trying to make a Entry widget that clears it's content when Esc is pressed.
Here's what I've tried -

class MyWindow(Gtk.Window):
    def __init__(self):
        Gtk.Window.__init__(self)
        editor = Gtk.Entry()
        self.add(editor)

I don't know what to connect the widget to. Esc is a keypress but the keypress should occur when the entry is in focus. I am totally lost.

Please help me make a entry that clears when Esc is pressed and it's in focus.

like image 877
svineet Avatar asked Nov 17 '13 07:11

svineet


1 Answers

You could connect Gtk.Entry to either "key-press-event" or/and "key-release-event" to receive notification about the key being pressed or released for the entry widget. The callback will be called when entry receives key-press/release events for which it has to be in focus. To to check if Escape key has been pressed you can make use of the event passed to the callback. You can check the keyval (which is associated with Gdk.Event.KEY_PRESS and Gdk.Event.KEY_RELEASE). You can make use of Gdk.KEY_* to check for the value of the key which was pressed or released. You can try something on the lines of:

...
    def on_key_release(self, widget, ev, data=None):
        if ev.keyval == Gdk.KEY_Escape: #If Escape pressed, reset text
            widget.set_text("")
...
    def __init__(self):
        Gtk.Window.__init__(self)
        editor = Gtk.Entry()
        editor.connect("key-release-event", self.on_key_release)   
        self.add(editor)

There is fair amount of documentation available online to aid you.
Hope this helps!

like image 171
another.anon.coward Avatar answered Oct 25 '22 04:10

another.anon.coward