我只是想使用键盘键从左向右移动图像。我尝试创建一个名为movableImage的类,它继承自Image。我认为这是我做错的地方,特别是 init 功能。当我运行下面的代码时,我得到了AttributeError:'function'对象在第16行没有属性'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()
我还应该补充一点,我已经阅读了Kivy keyboardlistener示例,但我仍然卡住了。
答案 0 :(得分:4)
以下是您正在尝试执行的操作示例,只需运行它并使用向右/向左箭头键向右/向左移动:
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()
您遇到的问题是request_keyboard是一个函数,需要以这种方式调用。您也可以删除if self._keyboard.widget:
部分。