Ad

How Can I Direct To Next Page And Also Call A Function On A Button Click In Kivy?

- 1 answer

I have a application with two buttons on first screen. I want both the buttons to route to next page and simultaneously call their respective funtions. Can anyone help me with link or codes. Thanks in advance.

Ad

Answer

The following example illustrates using Kivy ScreenManager, Button widgets and button's on_release and on_press events.

main.py

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()
Ad
source: stackoverflow.com
Ad