Reputation: 6785
I am simply trying to move an image from left to right using the keyboard keys. I tried making a class called movableImage that inherits from Image. I think this is where I did something wrong, specifically the init function. When I run the code below I am getting AttributeError: 'function' object has no attribute 'widget' on line 16. What am I doing wrong here?
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()
I should also add that I HAVE read the Kivy keyboardlistener example and I am still stuck.
Upvotes: 1
Views: 2815
Reputation: 1347
Here's a working example of what you're trying to do, just run it and use the right / left arrow keys to move it right / left:
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()
The problem you ran into, is that request_keyboard is a function, and needs to be called that way. You can also remove the if self._keyboard.widget:
part.
Upvotes: 7