2017-02-26 108 views
0

很抱歉,如果图像是巨大的访问儿童IDS的孩子KIvy

Sorry if the image is huge

确定。所以here's my complete code。它是中等大小的,所以它仅供参考 - 不需要理解代码。因此,如果我想访问Python中Layout中的Button(),Label()或TextInput()对象,我只需要执行self.ids.object_name.property_of_object即可。

但是,假设我有一个ScreenManager(),该ScreenManager()中的Screen()以及该屏幕对象内的自定义布局MyCustomLayout()。就我所能得到的结果而言 - 我无法从Screen()的Python代码中获取MyCustomLayout()中的id。

I.e.假设在MyCustomLayout()中有一个按钮my_button的id。我想改变文字。

如果我是类MyCustomLayout()下,这将工作:

self.ids.my_button.text = 'My new text!' 

但是,假设我在自选画面(),它保存MyCustomLayout()。我一直没能得到:

self.ids.my_button.text doesn't work 
self.ids.my_custom_layout.my_button.text doesn't work 

事实上,self.ids返回{}。由于某种原因,它甚至没有填充ObservableDict。

但是,无论如何。我想我说的是这个。如果我要访问自定义窗口小部件的孩子:

  1. 在一个屏幕对象
  2. 在Python
  3. 在自选画面()类

我会怎么做呢?

谢谢!

额外的信用:告诉我你是如何学到这些的!

回答

1

您可以在kvlang中为对象提供一个id。 id: mybutton
在以下示例中,我在第一个屏幕的输入上将该按钮的文本设置为随机数字。
在第二个屏幕上,我输入时只是从该屏幕及其子中打印所有ID。

from kivy.app import App 
from kivy.uix.screenmanager import ScreenManager, Screen 
from kivy.lang import Builder 
from kivy.uix.boxlayout import BoxLayout 
from random import choice 

Builder.load_string(''' 


<MyCustomLayout1>: 
    Button: 
     id: mybutton 
     text: "Goto 2" 
     on_release: app.sm.current = "screen2" 


<MyCustomLayout2>: 
    Button: 
     id: mybutton 
     text: "Goto 1" 
     on_release: app.sm.current = "screen1" 


<Screen1>: 
    MyCustomLayout1: 
     id: mylayout 

<Screen2>: 
    MyCustomLayout2: 
     id: mylayout 

''') 


class Screen1(Screen): 

    def on_enter(self,*args): 
     self.ids.mylayout.ids.mybutton.text = str(choice(range(100))) 


class Screen2(Screen): 

    def on_enter(self,*args): 
     print(self.ids) 
     print(self.ids.mylayout.ids) 


class MyCustomLayout1(BoxLayout): 
    pass 

class MyCustomLayout2(BoxLayout): 
    pass 


class MyApp(App): 
    def build(self): 
     self.sm = ScreenManager() 
     self.sm.add_widget(Screen1(name='screen1')) 
     self.sm.add_widget(Screen2(name='screen2')) 
     return self.sm 


MyApp().run() 

当你嵌套对象时,你可以做obj.ids.obj.ids等等。
即使它不是问题的一部分,我可以提一下,为了从boxlayout访问screenmanager,最好让screenmanager成为App类的一个属性。这样,你认为它在kvlang作为app.sm

你结束你的问题,问我在哪里了解到这一点。
好吧,你完全正确的,你只是没有得到嵌套的权利。我从kivy的api参考文件kvlang了解到kvlang。我不记得它是否对嵌套有很多说明。但希望在这个例子中,这似乎是一个合乎逻辑的方式。

+0

啊,我很高兴你这样回答。给我一个机会来更具体地说明我在询问什么。让我们拿你的代码,但修改BoxLayout的一部分,就像这样 - Gist:https://gist.github.com/Crowbrammer/d78ea1a3491db095021bbabc4744b99b –

+0

因为,在Screens中实例化一个自定义类会产生一个'mybutton'的KeyError。如果我拿出第40-41行,我得到一个AttributeError - 'MyCustomLayout1'没有属性'manager'(它没有)。所以,问题是,我们如何使这个新代码 - 使用自定义类 - 像您的原始代码一样工作? –

+0

@crowbar编程啊:)我会看看 – EL3PHANTEN