简体   繁体   English

当Gtk.Entry处于焦点时检测按键

[英]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. 我试图创建一个Entry小部件,在按下Esc时清除它的内容。
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. Esc是一个按键,但是当条目成为焦点时应该发生按键。 I am totally lost. 我完全迷失了。

Please help me make a entry that clears when Esc is pressed and it's in focus. 当Esc被按下并且它处于焦点时,请帮我做一个清除的条目。

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. 您可以将Gtk.Entry连接到"key-press-event"或/和"key-release-event"以接收有关为条目窗口小部件按下或释放的键的通知。 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. 要检查是否已按下Escape键,您可以使用传递给回调的事件 You can check the keyval (which is associated with Gdk.Event.KEY_PRESS and Gdk.Event.KEY_RELEASE ). 您可以检查keyval(与Gdk.Event.KEY_PRESSGdk.Event.KEY_RELEASE相关联)。 You can make use of Gdk.KEY_* to check for the value of the key which was pressed or released. 您可以使用Gdk.KEY_*来检查按下或释放的键的值。 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! 希望这可以帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM