2016-02-03 62 views
0

我是新来的kivy框架,我不认为我正确理解kv文件和python之间的id引用是如何工作的。当我用纯python编码时,它按预期工作,但我试图学习使用布局语言。我有动态生成分散小部件,我需要将它们添加到布局。Keyerror在Kivy布局语言

在python中。

class MainScreen(Screen): 
    def on_enter(self): 

     for index in xrange(numberOfWords): 
       genColor = [255, 0, 0] 
       shuffle(genColor) 
       newWordWidget = WordWidget(genColor) 
       if newWordWidget.label.color[0] == 255 and newWordWidget.label.text != 'red': newWordWidget.trash = True 
       if newWordWidget.label.color[1] == 255 and newWordWidget.label.text != 'green': newWordWidget.trash = True 
       if newWordWidget.label.color[2] == 255 and newWordWidget.label.text != 'blue': newWordWidget.trash = True 
       print("Trash:" + str(newWordWidget.trash)) 
       newWordWidget.scatter.pos = randint(0, Window.size[0]), randint(0, Window.size[1]) 
       self.ids.widgetscreen.add_widget(newWordWidget.scatter) 

的KV文件:

<FloatLayout>: 
ScreenManagement: 
    MainScreen: 
<MainScreen>: 
    FloatLayout: 
     id: widgetscreen 
     canvas: 
      Color: 
       rgba: 1, 1, 1, 1 
      Rectangle: 
       pos: self.pos 
       size: self.size 

我收到就行了KeyError异常:ID:widgetscreen。

回答

1

这解决了我的问题。

从我原来的职位蟒蛇:

from kivy.clock import mainthread 

和...

class MainScreen(Screen): 
    @mainthread 
    def on_enter(self): 

没有什么是错的id引用。问题是在引用id之后加载的kv文件。 @mainthread使得def on_enter()等待加载kv文件。

+0

这确实解决了这个问题,但它通常被认为是单一的。对于大多数目的,不鼓励使用'ids'属性。 – Kwarrtz

1

做元素链接的建议方式就像这样。

KV:

<MainScreen>: 
    widgetscreen: wdscreen 
    FloatLayout: 
     id : wdscreen 
     ... 

的Python:

from kivy.properties import ObjectProperty # don't forget to add the import 

class MainScreen(Screen): 

    widgetscreen = ObjectProperty(None) 
    .... 

让我们来看看这里发生了什么。首先,在Python代码中,我们创建了一个类属性MainScreen,widgetscreen,默认为None。然后,在我们的KV文件中,我们将该属性MainScreen设置为wdscreen。在KV lang中,IDS像变量一样工作,所以当我们将widgetscreen设置为wdscreen时,我们实际上将其设置为我们使用ID wdscreen定义的FloatLayout。在运行时,kivy将用适当的小部件填充我们的Python属性。

因此,您应该可以从MainScreen中获得widgetscreen作为self.widgetscreen。你甚至不需要使用ids

+0

不起作用。获取“ObjectProperty”未定义错误。 –

+0

@SteveHostetler,将'ObjectProperty'添加到您的导入列表中。 (例如'from kivy.properties import ObjectProperty') – Kwarrtz