Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you check for keyboard events with kivy?

Tags:

So, awhile ago, I started teaching myself kivy. I started with the main kivy website and went through its pong making tutorial and upon finishing that I decided to try and give it key input. I just can't seem to find any kind of guide to key input with kivy! Anyone know some kind of tutorial or can provide some easy to understand code? I did look at the Keyboard Listener in the examples folder of kivy, but I'm not quite sure how to use that if I'm supposed to.

Thanks for any assistance.

like image 402
Alex Avatar asked Jun 24 '13 16:06

Alex


People also ask

How do I change button size on KIVY?

To change the size and position of a button in kivy, we use four properties: size, pos,size_hint, and post_hint. Out of these four properties, size and pos properties are used for static placement of widgets and size_hint and pos_hint properties for dynamic placement of the widgets.


1 Answers

I guess you are asking how to control the paddles with the keyboard. I assume you have the final ping pong codes running on your computer (If not, you can find them at the end of this section).

1 - In the main.py import the Window class:

from kivy.core.window import Window 

2 - Redefine the beginning of the PongGame class so it looks like the following:

class PongGame(Widget):     ball = ObjectProperty(None)     player1 = ObjectProperty(None)     player2 = ObjectProperty(None)      def __init__(self, **kwargs):         super(PongGame, 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':             self.player1.center_y += 10         elif keycode[1] == 's':             self.player1.center_y -= 10         elif keycode[1] == 'up':             self.player2.center_y += 10         elif keycode[1] == 'down':             self.player2.center_y -= 10         return True 

Voilà! Press w and s for the left paddle and up and down for the right paddle.

like image 73
toto_tico Avatar answered Sep 18 '22 05:09

toto_tico