get values from a different screen (kivy)

2019-04-16 21:50发布

I´m trying to achieve the following: capture the text from from Label: id: fb in screen FolderB and copy/add to Label: id: fa in screen FolderA by pressing the Button "get the txt from Folder B". Please find the codes below: Thanks in advance,

file main.py

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

Builder.load_file('foldera.kv')
Builder.load_file('folderb.kv')

class MainScreen(ScreenManager):
    pass

class FolderA(Screen):
    pass

class FolderB(Screen):
    pass

class FTest(App):
    def build(self):
        return MainScreen()


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

file ftest.kv (class build)

<FolderA@FolderA>
<FolderB@FolderB>

<MainScreen>:
    FolderA:
        name: 'foldera'
    FolderB:
        name: 'folderb'

file foldera.kv (boxlayout)

<FolderA>:
    BoxLayout:
        orientation: 'vertical'
        Label:
            text: 'Folder A'
        Button:
            text: 'go to Folder B'
            on_press: app.root.current = 'folderb'
        Label:
            id: fa
            text: ''
        Button:
            text: 'get text from Folder B'
            on_press: "this is the button where i'm trying to apply the action"

file folderb.kv (boxlayout)

<FolderB>:
    BoxLayout:
        orientation: 'vertical'
        Label:
            text: 'Folder B'
        Button:
            text: 'go to Folder B'
            on_press: app.root.current = 'foldera'
        Label:
            id: fb
            text: 'TEXT: CAPTURE THIS TEXT'

screenshot

Img01 Img02

1条回答
霸刀☆藐视天下
2楼-- · 2019-04-16 22:04

You could save the shared variable in the App class, for example.
Then you can access it in kv, by writing app.label_a
Try this example:

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

Builder.load_string("""
<Manager>:
    Screen:
        name: 'first'
        BoxLayout:
            Label:
                text: app.label_a
            Button:
                text:'go to other'
                on_press: app.sm.current = 'other'

    Screen:
        name: 'other'
        BoxLayout:
            Label:
                id: label_b
                text: "Screen 2 label. Press button to change."
            Button:
                text:'Get label text from screen 1'
                on_press: label_b.text = app.label_a    
""")


class Manager(ScreenManager):
    pass


class MyApp(App):
    label_a = StringProperty("Screen 1 Label")

    def build(self):
        self.sm = Manager()
        return self.sm    

MyApp().run()
查看更多
登录 后发表回答