【发布时间】:2015-05-06 20:56:58
【问题描述】:
我现在正在 Raspberry-Pi 上学习使用 kivy。我安装了最新的 kivypie 图像,我确实想制作一个简单的应用程序,它可以更改图像内容以及按钮和按键上的一些标签。
按钮按预期工作,但在键盘上按 uo/down 键后,只有标签文本发生变化,没有显示图像。
我也可以按 q 按钮退出应用程序,但不能按我想要的退出按钮。
这是我当前的代码:
from kivy.app import App
from kivy.uix.widget import Widget
from kivy.uix.button import Button
from kivy.uix.label import Label
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.image import Image
from kivy.core.window import Window
class MyApp(App):
def build(self):
self._keyboard = Window.request_keyboard(self._keyboard_closed, self)
self._keyboard.bind(on_key_down=self._on_keyboard_down)
root = BoxLayout(orientation='vertical')
self.image = Image(source='test.png',
allow_stretch=True,
keep_ratio=True)
root.add_widget(self.image)
self.label = Label(text='Some long and very explanatory text. This is a representation of a custom image description'
' coming with the image. This text can split over several lines and will fit in a box'
'defined by the text_size property.',
font_size=28,
text_size=(600, None),
color=(0, 1, 1, 1),
size_hint=(1, .2))
root.add_widget(self.label)
button = Button(text="Change",
size_hint=(1, .07))
button.bind(on_press=self.callback)
root.add_widget(button)
return root
def callback(self, value):
self.image.source = 'test.jpg'
self.label.text = 'No text'
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):
#print('### ----------------------------------- ###')
#print('The key', keycode, 'have been pressed')
#print(' - text is %r' % text)
#print(' - modifiers are %r' % modifiers)
if text == 'escape':
App.get_running_app().stop()
#keyboard.release()
elif text == 'q':
App.get_running_app().stop()
#keyboard.release()
elif text == 'up':
self.image.source = 'test.jpg'
self.label.text = 'No text'
#keyboard.release()
elif text == 'down':
self.image.source = 'test.jpg'
self.label.text = 'No text'
#keyboard.release()
return True
if __name__ == '__main__':
MyApp().run()
【问题讨论】:
-
您发布的代码没有执行。您在
build(self)中存在缩进问题,并且您正在引用不存在的属性。 -
stackoverflow 编辑器导致 build() 方法末尾缩进错误。我已经修好了。
标签: python keypress kivy keyboard-events