如何在 Kivy 中使用键盘移动图像?

dav*_*vid 1 keyboard-events kivy

我只是尝试使用键盘键从左到右移动图像。我尝试创建一个从 Image 继承的名为movableImage的类。我认为这是我做错的地方,特别是init函数。当我运行下面的代码时,我在第 16 行收到 AttributeError: 'function' object has no attribute 'widget'。我在这里做错了什么?

from kivy.app import App
from kivy.uix.widget import Widget
from kivy.uix.image import Image
from kivy.input.motionevent import MotionEvent
from kivy.core.window import Window


class character(Widget):
    pass

class moveableImage(Image):
    def __init__(self, **kwargs):
        super(moveableImage, self).__init__(**kwargs)
        self._keyboard = Window.request_keyboard
        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 on_keyboard_down(self, keyboard, keycode, text, modifiers):
        if keycode[1] == 'left':
            print keycode #move littleguy to the left
        elif keycode[1] == 'right':
            print keycode #move littleguy to the right
        return True

littleguy = moveableImage(source='selectionscreen/littleguy.zip', anim_available=True, anim_delay=.15)

class gameApp(App):
    def build(self):
        m = character()
        m.add_widget(littleguy)
        return m


if __name__ == '__main__':
    gameApp().run()
Run Code Online (Sandbox Code Playgroud)

我还应该补充一点,我已经阅读了 Kivy 键盘监听器示例,但我仍然被卡住了。

Mat*_*att 7

这是您尝试执行的操作的一个工作示例,只需运行它并使用右/左箭头键将其向右/向左移动:

from kivy.app import App
from kivy.uix.widget import Widget
from kivy.uix.image import Image
from kivy.core.window import Window


class character(Widget):
    pass


class MoveableImage(Image):

    def __init__(self, **kwargs):
        super(MoveableImage, self).__init__(**kwargs)
        self._keyboard = Window.request_keyboard(None, self)
        if not self._keyboard:
            return
        self._keyboard.bind(on_key_down=self.on_keyboard_down)

    def on_keyboard_down(self, keyboard, keycode, text, modifiers):
        if keycode[1] == 'left':
            self.x -= 10
        elif keycode[1] == 'right':
            self.x += 10
        else:
            return False
        return True


class gameApp(App):
    def build(self):
        wimg = MoveableImage(source='tools/theming/defaulttheme/slider_cursor.png')
        m = character()
        m.add_widget(wimg)
        return m


if __name__ == '__main__':
    gameApp().run()
Run Code Online (Sandbox Code Playgroud)

您遇到的问题是 request_keyboard 是一个函数,需要以这种方式调用。您也可以移除if self._keyboard.widget:零件。