在GUI中捕获特定的按键组合

时间:2019-03-07 23:50:55

标签: python kivy

我正在尝试捕获用户在我的应用程序中时按其键盘上的Ctrl + Enter:

class UI(Widget):
    def __init__(self, **kwargs):
        super(UI, self).__init__(**kwargs)
        self._keyboard = Window.request_keyboard(self._keyboard_closed, self)
        self._keyboard.bind(on_key_down=self._on_keyboard_down)

    def _keyboard_closed(self):
        self._keyboard.unbind(on_key_down=self._on_keyboard_down)
        self._keyboard = None

    def _on_keyboard_down(self, keyboard, keycode, text, modifiers):
        if keycode[1] == 'w':
            print("yes")
            return False
        return True


class UIApp(App):
    def build(self):
        return UI()

UIApp().run()

我意识到这段代码将捕获w,但它甚至没有做到这一点。或至少不会打印到控制台。我的用户界面:

#:kivy 1.0.9

<UI>:
    title: 'InputDialog'
    auto_dismiss: False

    RelativeLayout:
        ...

1 个答案:

答案 0 :(得分:0)

检查modifiers[0] == 'ctrl'keycode[0] == 13text is None

def _on_keyboard_down(self, keyboard, keycode, text, modifiers):
    if len(modifiers) > 0 and modifiers[0] == 'ctrl' and keycode[0] == 13:     
        # ctrl + enter pressed
        print("\nThe key", keycode, "have been pressed")
        print(" - text is %r" % text)
        print(" - modifiers are %r" % modifiers)