我现在正在学习在我的树莓派上使用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()
发布于 2015-05-07 17:07:05
如果取消对打印语句的注释,您将看到要查找的信息是keycode
格式的,而不是text
格式的。text
将只匹配字母键,对于特殊键(转义、向上、向下等)则不匹配。尝试将其更改为:
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)
key = keycode[1]
if key == 'escape':
App.get_running_app().stop()
#keyboard.release()
elif key == 'q':
App.get_running_app().stop()
#keyboard.release()
elif key == 'up':
self.image.source = 'test2.png'
self.label.text = 'No text'
#keyboard.release()
elif key == 'down':
self.image.source = 'test2.png'
self.label.text = 'No text'
#keyboard.release()
return True
https://stackoverflow.com/questions/30087369
复制