我希望在键盘中按下一个键时执行一个函数。我想有一个简单的例子如何做到这一点,因为我想在我的应用程序中实现它。我会感谢任何帮助。
首先导入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())