如何理解一个kivy DictProperty

时间:2018-04-11 14:52:18

标签: python kivy

我想使用kivys DictObject并在其他屏幕中重用相同的对象,但我似乎缺少一个重要的功能,特别是迭代DictObject。这是我的代码:

test_data = {1: "hello", 2: "world"}


class AlarmScreen(Screen):      
    def on_enter(self, *args):
        self.printItems(mainApp.alarmLib)            

    def printItems(self, givenDict):
        for i in givenDict:
            print(i)  

class mainApp(App):
    alarmLib = DictProperty()

    def build(self):       
        self.alarmLib = test_data

if __name__ == "__main__":
    mainApp().run()

不幸的是printItems导致了

TypeError: 'kivy.properties.DictProperty' object is not iterable

我用enumerate(),items()来尝试它,但那不起作用。那么我可以使用DictObject通过多个屏幕与dictonary一起工作,还是我需要创建一个" old"用

命令对象
def __init__(self, givenDict):
    self.giveDict = givenDict

为此?

提前感谢您的提示。

1 个答案:

答案 0 :(得分:0)

  1. mainApp.alarmLib是一个名为= alarmLib的DictProperty。需要定义构造函数(__init__)方法。
  2. 显示DictProperty如下:
  3. 片段

    for key in givenDict:
        print("key={0}, value={1}".format(key, givenDict[key]))
    

    实施例

    main.py

    from kivy.app import App
    from kivy.properties import DictProperty
    from kivy.uix.screenmanager import ScreenManager, Screen
    
    
    test_data = {1: "hello", 2: "world"}
    
    
    class AlarmScreen(Screen):
        parmDict = DictProperty({})
    
        def __init__(self, parmDict, **kwargs):
            super(AlarmScreen, self).__init__(**kwargs)
            self.parmDict = parmDict
    
        def on_enter(self, *args):
            self.printItems(self.parmDict)
    
        def printItems(self, givenDict):
            for key in givenDict:
                print("key={0}, value={1}".format(key, givenDict[key]))
    
    
    class mainApp(App):
        alarmLib = DictProperty({})
    
        def build(self):
            self.alarmLib = test_data
            sm = ScreenManager()
            sm.add_widget(AlarmScreen(name='alarmscreen', parmDict=self.alarmLib))
            return sm
    
    
    if __name__ == "__main__":
        mainApp().run()
    

    输出

    Img01 - DictProperty Displayed