Gilgamesch
Gilgamesch

Reputation: 311

Exchanging Variables between Screens in kivy python

I tried to make an app, with two screens, one with an Textinput and the other one Label, that is displaying the Text of the TextInput. I tried to make this by creating an StringProperty in the app class, but I had a problem with accessing the Property. I would like to know how to access the Variable. Here is the source code:

from kivy.app import App
from kivy.lang import Builder
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.properties import StringProperty
from kivy.uix.boxlayout import BoxLayout


class Manager(ScreenManager):
    pass
class FirstScreen(Screen):
    pass
class SecondScreen(Screen):
    pass
root_widget = Builder.load_string('''
Manager:
    FirstScreen:
    SecondScreen:
<FirstScreen>:
    name: 'first'
    BoxLayout:
        orientation: 'vertical'
        TextInput:
            id: my_text
            font_size: 50
        Button:
            id: b1
            text: 'Go to next Screen'
            on_release: app.root.current = 'second'
<SecondScreen>:
    name: 'second'
    BoxLayout:
        orientation: 'vertical'
        Label:
            id: my_Label
            text: root.txt
        Button
            id: b2
            text: 'Go back'
            on_release: app.root.current = 'first'
''')
class Caption(App):
    txt = StringProperty('')
    def build(self):
        return root_widget

Caption().run()

Upvotes: 2

Views: 7860

Answers (1)

Tugberk Ayar
Tugberk Ayar

Reputation: 71

Screen class has an attribute called 'manager' which specifies which manager that screen belongs to. In ScreenManager class, there is an attribute called 'screens', which is a ListProperty object that holds all the screens. If you want to reach out an information about another screen, you can use this way. In your case, you need to update your your b1 id button in your kv Builder with this:

Button:
    id: b1
    text: 'Go to next screen'
    on_release:
        root.manager.screens[1].ids.my_Label.text = root.ids.my_text.text
        root.manager.current = 'second'

For more complex behaviours, you can define related Property in that particular Page class and reach out from python with:

self.manager.screens[<screen_number>].ids.<widget_id>.<property_name>

Upvotes: 5

Related Questions