在kivy python中交换屏幕之间的变量

时间:2015-01-03 18:27:20

标签: python-2.7 properties kivy

我尝试制作一个应用程序,有两个屏幕,一个带有Textinput,另一个带有Label,即显示TextInput的Text。 我尝试通过在app类中创建一个StringProperty来实现这一点,但是我在访问Property时遇到了问题。 我想知道如何访问变量。 这是源代码:

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

1 个答案:

答案 0 :(得分:0)

Screen类具有一个称为“ manager”的属性,该属性指定该屏幕属于哪个管理器。在ScreenManager类中,有一个名为“屏幕”的属性,它是一个ListProperty对象,用于保存所有屏幕。如果您想获得有关另一个屏幕的信息,可以使用这种方式。就您而言,您需要使用以下命令更新kv Builder中的b1 id按钮:

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'

对于更复杂的行为,您可以在该特定的Page类中定义相关的Property,并使用以下方法从python接触:

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