您如何用kivy检查键盘事件? [英] How do you check for keyboard events with kivy?

查看:193
本文介绍了您如何用kivy检查键盘事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,不久前,我开始自学猕猴桃.我先从主要的kivy网站开始,然后进行了有关pong制作的教程,并在完成后决定尝试为其提供关键输入.我似乎无法找到任何有关使用kivy进行键输入的指南!任何人都知道某种教程或可以提供一些易于理解的代码吗?我确实看过kivy的examples文件夹中的Keyboard Listener,但是我不确定如果应该怎么使用它.

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.

感谢您的帮助.

推荐答案

我猜您在问如何用键盘控制拨片.我假设您的计算机上正在运行最终的乒乓代码(如果没有,您可以在

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-在main.py中导入Window类:

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

from kivy.core.window import Window

2-重新定义PongGame类的开头,使其类似于以下内容:

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à!按下ws按下左拨片,按下updown按下右拨片.

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

这篇关于您如何用kivy检查键盘事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆