从不同的屏幕获取值(kivy)

时间:2018-06-04 19:48:03

标签: kivy kivy-language

我正在尝试实现以下功能:从Label中捕获文本:id:fb在屏幕FolderB中并复制/添加到Label:id:fa在屏幕FolderA中按下按钮“从文件夹B获取txt” 。请找到以下代码: 提前谢谢,

文件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'

截图

Img01 Img02

1 个答案:

答案 0 :(得分:0)

例如,您可以将共享变量保存在App类中 然后,您可以通过写app.label_a来以kv格式访问它 试试这个例子:

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()