我在第一个屏幕上有一个带有两个按钮的应用程序。我希望两个按钮都路由到下一页,同时调用它们各自的功能。 任何人都可以通过链接或代码帮助我。预先感谢。
答案 0 :(得分:0)
以下示例说明了如何使用Kivy ScreenManager
,Button
小部件以及按钮的on_release
和on_press
事件。
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.screenmanager import ScreenManager, Screen
# Create both screens. Please note the root.manager.current: this is how
# you can control the ScreenManager from kv. Each screen has by default a
# property manager that gives you the instance of the ScreenManager used.
Builder.load_string("""
<ScreenManagement>:
MenuScreen:
id: name
name: 'menu'
SettingsScreen:
id: settings
name: 'settings'
<MenuScreen>:
BoxLayout:
Button:
text: 'Goto settings & invoke function abc'
on_release:
root.manager.current = 'settings'
root.manager.ids.settings.func_abc(self) # optional: passing Button instance
Button:
text: 'Goto settings & invoke function xyz'
on_release:
root.manager.current = 'settings'
root.manager.ids.settings.func_xyz(self) # optional: passing Button instance
<SettingsScreen>:
BoxLayout:
Button:
text: 'My settings button'
Button:
text: 'Back to menu'
on_press: root.manager.current = 'menu'
""")
# Declare both screens
class MenuScreen(Screen):
pass
class SettingsScreen(Screen):
def func_abc(self, instance):
print(f"func_abc: Called from Button with text={instance.text}")
def func_xyz(self, instance):
print(f"func_xyz: Called from Button with text={instance.text}")
# Create the screen manager
class ScreenManagement(ScreenManager):
pass
class TestApp(App):
def build(self):
return ScreenManagement()
if __name__ == '__main__':
TestApp().run()