簡體   English   中英

如果在 kivy python 中按下一個鍵(回車),則執行一個函數

[英]Do a function if a key(enter) is pressed in kivy python

我想要它,以便在 kivy 中按下一個鍵時執行一個功能。 我想有一個簡單的例子來說明如何做到這一點,因為我想在我的應用程序中實現它。 將不勝感激任何幫助。

首先導入Window類:

from kivy.core.window import Window

您可以創建一個處理鍵盤事件的函數:

class HiWorld(Widget):

    def __init__(self, **kwargs):
        super(HiWorld, 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] == 'e': #for example if you hit the key "e"
            self.do_something_e()
        elif keycode[1] == 'x': #if x is pressed
            self.do_something_x()
        return True
    def do_something_e(self):
        print("You pressed e")
    def do_something_x(self):
        print("You pressed x")
        

或者您可以使用官方示例表單kivy文檔:

import kivy
kivy.require('1.0.8')

from kivy.core.window import Window
from kivy.uix.widget import Widget


class MyKeyboardListener(Widget):

    def __init__(self, **kwargs):
        super(MyKeyboardListener, self).__init__(**kwargs)
        self._keyboard = Window.request_keyboard(
            self._keyboard_closed, self, 'text')
        if self._keyboard.widget:
            # If it exists, this widget is a VKeyboard object which you can use
            # to change the keyboard layout.
            pass
        self._keyboard.bind(on_key_down=self._on_keyboard_down)

    def _keyboard_closed(self):
        print('My keyboard have been closed!')
        self._keyboard.unbind(on_key_down=self._on_keyboard_down)
        self._keyboard = None

    def _on_keyboard_down(self, keyboard, keycode, text, modifiers):
        print('The key', keycode, 'have been pressed')
        print(' - text is %r' % text)
        print(' - modifiers are %r' % modifiers)

        # Keycode is composed of an integer + a string
        # If we hit escape, release the keyboard
        if keycode[1] == 'escape':
            keyboard.release()

        # Return True to accept the key. Otherwise, it will be used by
        # the system.
        return True


if __name__ == '__main__':
    from kivy.base import runTouchApp
    runTouchApp(MyKeyboardListener())

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM