2017-04-08 64 views
0

我在解析Kivy中的構件時會遇到問題,然後訪問該構件並能夠在屏幕上顯示值,並通過時鐘間隔(不是肯定還有更好的做到這一點呢)。Kivy - 將結構解析爲構件

我強調這些問題在下面的(非工作)代碼:

main.py

from kivy.app import App 
from test import TestWidget 

class TestApp(App): 

    def build(self): 
     testStructTable = {'randomVal1': 1, 'testVal': 2, 'randomVal2': 3} 

     # Issue here parsing the table like this? 
     return TestWidget(testStructTable) 

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

test.py

from kivy.lang import Builder 
from kivy.uix.screenmanager import ScreenManager, Screen 
from kivy.uix.relativelayout import RelativeLayout 
from kivy.properties import NumericProperty 


class TestWidget(RelativeLayout): 

    def __init__(self, testStructTable, **kwargs): 
     super(TestWidget, self).__init__(**kwargs) 
     Builder.load_file('test.kv') 

     sm = ScreenManager() 
     sm.add_widget(MainScreen(name='MainScreen')) 
     self.add_widget(sm) 

     # Error accessing the table 
     print self.testStructTable 

     # Have the update_test_val continuously called 
     #Clock.schedule_interval(MainScreen.update_test_val(testStructTable), 1/60) 


class MainScreen(Screen): 

    def __init__(self, **kwargs): 
     testVal = NumericProperty(0) 

    def update_test_val(self, testStructTable): 
     # Get testVal from testStructTable 
     # Something like: 
     # self.testVal = testStructTable.testVal + 1 ? 
     self.testVal = self.testVal + 1 

測試。 kv

<MainScreen>: 
    FloatLayout: 
     Label: 
      text: str(root.testVal) 
      font_size: 80 

我的目標是通過訪問該數據結構讓testVal在屏幕上不斷更新,但是我目前無法實現這一點,請問您能提供建議嗎?

回答

1

在你__init__方法你傳遞testStructTable,然後你要訪問self.testStructTable不存在,直到您明確地進行分配:

from kivy.app import App 
from kivy.lang import Builder 
from kivy.uix.screenmanager import ScreenManager, Screen 
from kivy.uix.relativelayout import RelativeLayout 
from kivy.properties import NumericProperty 


class TestWidget(RelativeLayout): 
    def __init__(self, testStructTable, **kwargs): 
     super(TestWidget, self).__init__(**kwargs) 

     print(testStructTable) 
     self.testStructTable = testStructTable 
     print(self.testStructTable) 


class TestApp(App): 
    def build(self): 
     testStructTable = {'randomVal1': 1, 'testVal': 2, 'randomVal2': 3} 
     # Issue here parsing the table like this? 
     return TestWidget(testStructTable) 

if __name__ == '__main__': 
    TestApp().run() 
+0

這是工作,謝謝!你也可以建議如何讓那個testVal在屏幕上不斷更新嗎? – Rekovni

+0

使用與'kivy.clock'模塊結合使用的屬性是正確的方法。 kivy中的屬性實現了觀察者模式,所以對它們的任何改變都可以立即反映在你的小部件中。有關示例,請參見[這裏](http://www.gurayyildirim.com.tr/kivy-course-5-properties-and-clock-definitions-1191.html)。 – Nykakin