scan
scan

Reputation: 107

i cant clear root in kivy

I want to clean the screen and bring new widgets depending on some buttons or situations. first page second page etc ..

But either I bring the widgets onto the old ones or I have problems that I don't understand.

here are my codes

main.py

from kivy.app import App

class PageOne(App):
    def p_1(self):
        self.root.clear_widgets()
        PageTwo().run()

    def build(self, *args):
        pass

class PageTwo(App):
    def p_2(self):
        self.root.clear_widgets()
        PageOne().run()

    def build(self):
        pass

PageOne().run()

pageone.kv :

FloatLayout:
    Label:
        size_hint: 1, 0.7
        pos_hint: {"top":1}
        text: "Page 1"
    Button:
        size_hint: 1, 0.3
        pos_hint: {"top": 0.3}
        text: "Open Page 2"
        on_press: app.p_1()

pagetwo.kv :

FloatLayout:
    Label:
        size_hint: 1, 0.5
        pos_hint: {"top":1}
        text: "Page 2"
    Button:
        size_hint: 1, 0.3
        pos_hint: {"top": 0.3}
        text: "Open Page 1"
        on_press: app.p_2()

some warnings

[INFO   ] [MTD         ] Read event from </dev/input/event6>
[INFO   ] [Base        ] Start application main loop
[WARNING] [MTD         ] Unable to open device "/dev/input/event6". Please ensure you have the appropriate permissions.
[WARNING] [MTD         ] Unable to open device "/dev/input/event6". Please ensure you have the appropriate permissions.
[INFO   ] [Base        ] Leaving application in progress...
.
.
 AttributeError: 'PageOne' object has no attribute 'p_2'

What am I doing wrong!? thanks in advance

Upvotes: 0

Views: 894

Answers (1)

eyllanesc
eyllanesc

Reputation: 244132

There can only be one App, if you want to have several views you should use several Screen with a ScreenManager, for example:

from kivy.app import App
from kivy.lang import Builder
from kivy.uix.screenmanager import ScreenManager, Screen


class PageOne(Screen):
    def p_1(self):
        self.manager.current = 'PageTwo'

class PageTwo(Screen):
    def p_2(self):
        self.manager.current = 'PageOne'

Builder.load_string('''
<PageOne>:
    FloatLayout:
        Label:
            size_hint: 1, 0.7
            pos_hint: {"top":1}
            text: "Page 1"
        Button:
            size_hint: 1, 0.3
            pos_hint: {"top": 0.3}
            text: "Open Page 2"
            on_press: root.p_1()

<PageTwo>:
    FloatLayout:
        Label:
            size_hint: 1, 0.5
            pos_hint: {"top":1}
            text: "Page 2"
        Button:
            size_hint: 1, 0.3
            pos_hint: {"top": 0.3}
            text: "Open Page 1"
            on_press: root.p_2()
''')

manager = ScreenManager()
manager.add_widget(PageOne(name="PageOne"))
manager.add_widget(PageTwo(name="PageTwo"))

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

if __name__ == '__main__':
    MainApp().run()

Upvotes: 1

Related Questions