从ScreenManager访问kivy语言的数据

时间:2015-06-14 01:58:49

标签: python kivy

如何从MyScreenManager访问kivy数据?如何访问Hellow或Timer数据?我不能在Hellow中使用on_release:root.starttimer()。

class Hellow(Screen):
    pass

class Timer(Screen):
    pass

class MyScreenManager(ScreenManager):
    def starttimer(self):
        #change text Hellow Button


root_widget = Builder.load_string('''
#:import FadeTransition kivy.uix.screenmanager.FadeTransition
MyScreenManager:
    transition: FadeTransition()
    Hellow:
    Timer:
<Hellow>:
    AnchorLayout:
        Button:
            id: but
            size_hint: None, None
            size:300,100
            text: 'make a foto'
            font_size: 30
            on_release: app.root.starttimer()

<Timer>:
    name: 'Timer'
''')



class ScreenManagerApp(App):
    def build(self):
        print(self.ids)
        return root_widget

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

stackoverflow的一些文本(它表示我需要输入更多文本),

1 个答案:

答案 0 :(得分:2)

屏幕管理器仅用于接受屏幕小部件,如果您尝试添加任何其他内容(如按钮或标签),则会引发异常。 kivy.uix.screenmanager.ScreenManagerException: ScreenManager accepts only Screen widget. .kv文件只允许一个根对象在您的情况下,您可以相互访问hello或Timer。

<Hellow>:
    name: 'hello'
    ...
    Button:
        id: but
        ...
        on_release: root.parent.current = 'Timer'

<Timer>:
    name: 'Timer'
    Button:
        text: "Take me back to hellow"
        on_release: root.parent.current = 'hello' 

但也可能有另一种方式。

<Main>:
    BoxLayout:
        Button:
            text: "Hello"
            on_release: sm.current = 'Timer'
            on_release: print(lbl.text)

        Button:
            text: "Timer"
            on_release: sm.current = 'Hello'
    ScreenManager:
        id: sm
        Screen:
            name: hello
            Label:
                id: lbl
                text: "I am hello"

        Screen:
            name: timer
            Label:
                text: "I am timer"

编辑1:

正如你在评论中提到的那样

class MyScreenManager(ScreenManager):
    def __init__(self,**kwargs):
        super(MyScreenManager,self).__init__(**kwargs)


    def starttimer(self,event):
        #print event.text
        event.text = "changed text"

<Hellow>:
    ...
    Button:
        ...
        on_release: root.parent.starttimer(self)