Search code examples
pythonkivykivy-language

Kivy ScreenManager switch screens leaving buttons


I am using ScreenManager to swicth screens but when I switch screens normally the buttons on that screen stay with it. I have to copy the buttons to each screen. Is there a way to switch screens while leaving the buttons in place?

This is my app code as it stands:

import (...)


class AppContainer(FloatLayout):
    pass


class NavButtons(BoxLayout):
    pass


class FirstScreen(Screen):
    pass


class SecondScreen(Screen):
    pass


class Screens(ScreenManager):
    pass


class MainApp(App):
    def build(self):
        return AppContainer()

(...)

and the kv file looks like this:

#:import BoxLayout kivy.uix.boxlayout.BoxLayout

<AppContainer>:
    NavButtons:
    Screens:
        FirstScreen:
        SecondScreen:
        ThirdScreen:


<NavButtons>:
    orientation:'vertical'
    Button:
        on_press: root.manager.current="first"
        text: 'First'
        pos_hint:{"top": 1, "left": 0}
    Button:
        on_press: root.manager.current="second"
        text: 'Second'
        pos_hint:{"top":0.8, "left": 0}
<Button>:
    size_hint: 0.2, 0.2


<FirstScreen>:
    name: "first"
    Label:
        text: "First Screen"


<SecondScreen>:
    name: "second"
    Label:
        text: "Second Screen"

But this throws an error: AttributeError: 'NavButtons' object has no attribute 'manager'

Any ideas?


Solution

  • in the field of the button the root is NavButtons, and as you can see NavButtons does not have Screens as a children, a way to access Screens is through app.root that returns in this case to AppContainer, we set it up to Screens and we access this because he is a children.

    #:import BoxLayout kivy.uix.boxlayout.BoxLayout
    
    <AppContainer>:
        NavButtons:
        Screens:
            id: sm
            FirstScreen:
            SecondScreen:
    
    <NavButtons>:
        orientation:'vertical'
        Button:
            on_press: app.root.ids.sm.current="first"
            text: 'First'
            pos_hint:{"top": 1, "left": 0}
        Button:
            on_press: app.root.ids.sm.current ="second"
            text: 'Second'
            pos_hint:{"top":0.8, "left": 0}
    
    [...]