2017-02-26 107 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