我是Kivy的新手,我有一个我自己无法解决的问题。 我有一个简单的应用程序,要在其中切换图像(MainScreen)。
这是代码:
IMAGE_SIZE = (640, 480)
class MainScreen(Screen):
def __init__(self, path, **kwargs):
super(MainScreen, self).__init__(**kwargs)
Window.size = (IMAGE_SIZE[0], IMAGE_SIZE[1])
with self.canvas:
self.bg = Image(path)
self.bind(pos=self.update_bg)
self.bind(size=self.update_bg)
self._keyboard = Window.request_keyboard(
self._keyboard_closed, self, 'text')
self._keyboard.bind(on_key_down=self._on_keyboard_down)
def update_bg(self, *args):
self.bg.pos = self.pos
self.bg.size = self.size
def _keyboard_closed(self):
print('My keyboard have been closed!')
self._keyboard.unbind(on_key_down=self._on_keyboard_down)
self._keyboard = None
def _on_keyboard_down(self, keyboard, keycode, text, modifiers):
if keycode[1] == 'escape':
keyboard.release()
if keycode[1] == 'enter':
print('before enter', screen_manager.current_screen)
screen_manager.transition.direction = 'left'
screen_manager.current_screen = scree_1
print('after enter',screen_manager.current_screen)
return True
screen_manager = None
scree_1 = MainScreen(path_1, name="1")
scree_2 = MainScreen(path_2, name="2")
class MyApp(App):
def build(self):
global screen_manager
screen_manager = ScreenManager()
screen_manager.add_widget(scree_2)
screen_manager.add_widget(scree_1)
return screen_manager
if __name__ == '__main__':
MyApp().run()
我进行了打印,以查看屏幕管理器是否有所更改:
在我看来,经理确实在改变屏幕,但是我还是一样。
我已经研究了这个问题,但发现没有任何帮助。
如果有人知道我在做什么错,我将不胜感激。
更新:
@JohnAnderson在评论中注意到,我应该交换屏幕的名称,而不是屏幕本身,但是没有任何改变。
答案 0 :(得分:1)
您必须操作的是screen_manager.current
,而不是screen_manager.current_screen
。
您还必须通过其名称引用screen
。
这是您的代码,正在运行:
IMAGE_SIZE = (640, 480)
class MainScreen(Screen):
def __init__(self, path, **kwargs):
super(MainScreen, self).__init__(**kwargs)
Window.size = (IMAGE_SIZE[0], IMAGE_SIZE[1])
with self.canvas:
self.bg = Image(source=path)
self.bind(pos=self.update_bg)
self.bind(size=self.update_bg)
self._keyboard = Window.request_keyboard(self._keyboard_closed, self, 'text')
self._keyboard.bind(on_key_down=self._on_keyboard_down)
def update_bg(self, *args):
self.bg.pos = self.pos
self.bg.size = self.size
def _keyboard_closed(self):
print('My keyboard have been closed!')
self._keyboard.unbind(on_key_down=self._on_keyboard_down)
self._keyboard = None
def _on_keyboard_down(self, keyboard, keycode, text, modifiers):
if keycode[1] == 'escape':
keyboard.release()
if keycode[1] == 'enter':
print('before enter', screen_manager.current)
screen_manager.transition.direction = 'left'
screen_manager.current = "1"
print('after enter', screen_manager.current)
return True
screen_manager = None
scree_1 = MainScreen(path_1, name="1")
scree_2 = MainScreen(path_2, name="2")
class MyApp(App):
def build(self):
global screen_manager
screen_manager = ScreenManager()
screen_manager.add_widget(scree_2)
screen_manager.add_widget(scree_1)
return screen_manager
if __name__ == '__main__':
MyApp().run()
答案 1 :(得分:0)
经过一番挖掘,我找到了另一个答案。 我也可以使用:
screen_manager.switch_to(screen_1, direction='left')