在GUI中捕获特定的键组合

2024-06-16 10:31:47 发布

您现在位置:Python中文网/ 问答频道 /正文

当用户在我的应用程序中按下键盘上的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:
        ...

Tags: keyselffalseuireturninitondef
1条回答
网友
1楼 · 发布于 2024-06-16 10:31:47

勾选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)

相关问题 更多 >