2016-04-08 39 views
0

我在main.py和spend.kv以下代碼如下kivy,斜面訪問app.root財產

main.py

from kivy.app import App 
from kivy.core.window import Window 
from kivy.uix.gridlayout import GridLayout 
from kivy.uix.relativelayout import RelativeLayout 
from kivy.uix.button import Button 
from kivy.uix.screenmanager import ScreenManager, Screen 

class Manager(ScreenManager): 
    currency = '$' 

class SpendApp(App): 
    def build(self): 
     control = Manager() 
     return control 

class First(Screen): 
    pass 

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

spend.kv

<Manager>: 
    First 


<First>: 
    GridLayout: 
     cols: 1 
     Label: 
      text: 'Total spending' 
      height: '48dp' 
      size_hint_y: None 
     Amount: 
      height: '38dp' 
      size_hint_y: None 
      font_color: 1,0,0,1 



<[email protected]>: 
    text: app.root.currency + '0.0' 

當我運行此程序崩潰與以下錯誤:

AttributeError: 'NoneType' object has no attribute 'currency' 

我知道這是因爲我的全球化志願服務青年的我spend.kv 文件app.root.currency:

<[email protected]>: 
    text: app.root.currency + '0.0' 

那麼有沒有辦法正確地作出此引用,而不會收到此錯誤?

+0

您可能希望'currency'一個'StringProperty',使標籤文本得到更新時自動的'currency'改變。 – zeeMonkeez

回答

2

如果使用下面的代碼:

<[email protected]>: 
    text: str(root) # 

你會發現,Amount對象的根是Amount對象本身,因爲當你定義它,它在任何層次的還沒有。您可以訪問root widged只有真正的層級內:

<First>: 
    GridLayout: 
     cols: 1 
     Label: 
      text: str(root) 

在這個層次,root對象definied爲First類,這實際上是Screen小部件的一個實例的對象,所以你必須使用才能manager屬性要進入您的Manager類:

<First>: 
    GridLayout: 
     cols: 1 
     Label: 
      text: root.manager.currency + '0.0'