如何使用kivy screenmanager在其他屏幕中引用对象

时间:2016-12-31 09:17:24

标签: python python-2.7 kivy kivy-language

我正在尝试更新另一个屏幕中存在但尚未成功的字段。 当有人能告诉我这里做错了什么时,我会非常高兴。

myscreenskv.py:

false

的.py:

style = r'''
# File: myscreenskv.py
#: import myscreens myscreens

<ScreenManagement>:
    MainScreen:
    Screen1:
    Screen2:

<MainScreen>:
    name: 'main'
    mainlog:mainlog
    id: scrmain
    BoxLayout:
        orientation: "vertical"
        Label:
            text: "Main"
        Label:
            id: mainlog
        Button:
            text: "go to screen 1"
            on_press:
                app.root.current = "screen1"
                root.action1()
        Button:
            text: "go to screen 2"
            on_press:
                app.root.current = "screen2"
                root.action2()

<Screen1>:
    name: 'screen1'
    sc1log:sc1log
    id: scr1
    BoxLayout:
        orientation: "vertical"
        Label:
            text: "Screen1"
        Label:
            id: sc1log
        Button:
            text: "go to main screen"
            on_press: app.root.current = "main"
        Button:
            text: "go to screen 2"
            on_press: app.root.current = "screen2"

<Screen2>:
    name: 'screen2'
    id: scr2
    sc2log:sc2log
    BoxLayout:
        orientation: "vertical"
        Label:
            text: "Screen2"
        Label:
            id: sc2log
        Button:
            text: "go to main screen"
            on_press: app.root.current = "main"
        Button:
            text: "go to screen 1"
            on_press: app.root.current = "screen1"

'''

1 个答案:

答案 0 :(得分:2)

您正在尝试访问ids词典,这很不错,但在一个完全不同的实例中,这就是为什么会出现此错误:

AttributeError: 'super' object has no attribute '__getattr__'

您需要访问正确的实例,才能访问其属性,在您需要访问ScreenManager的情况下,才能访问其screens属性(实例列表),您可以从中进行所需的编辑,例如文本:

<强> MainScreen.action1():

self.manager.screens[1].sc1log.text = 'Coming from main'
# no ids, because you put it into a variable before

要了解其工作原理,请查看小部件树:

<MainScreen>:
    id: scrmain
    BoxLayout:
        Label:
        Label:
            id: mainlog
        Button:
        Button:

此处idsMainScreen中可从MainScreen().ids(实例)访问的字典,这是输出:

{'mainlog': <WeakProxy to <kivy.uix.label.Label object at 0x12345678>>}

这意味着您无法将根小部件真正分配到自己的字典中 - 至少不是这种方式+无论如何都没有意义,因为您可以只调用root,它会为您提供实例根小部件。