使用add_widget()实现Kivy规则的内在性

时间:2015-07-24 23:36:12

标签: python kivy

跟进问题:Kivy outside rule inherence

main.py

from kivy.app import App
from kivy.uix.button import Button
from kivy.uix.stacklayout import StackLayout
from kivy.properties import ObjectProperty
from kivy.factory import Factory


class FancyButton(Button):
    imp = ObjectProperty(None)


class Important(StackLayout):

    def NoInspiration(self, smile):
        print("Received: {}".format(smile))

    def AddFancy(self):
        temp = Factory.FancyButton(text='f', imp = self.ids.imp)
        self.ids.boxy.add_widget(temp)


class TestApp(App):
    def build(self):
        pass

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

test.kv

#:kivy 1.9.0
#:import App kivy.app

<FancyButton>:
    on_release: self.imp.NoInspiration(':)')


<Important>:
    id: imp

    BoxLayout:
        id: boxy
        orientation: 'vertical'

        FancyButton:
            text: "smiley"
            imp: root

        Button:
            text: "add fancy"
            on_release: imp.AddFancy()


BoxLayout:
    Important

在test.kv中,FancyButton中的函数调用函数NoInspiration()起作用,因为.kv中定义的FancyButton有imp:root,所以它知道它应该在&lt;中查找函数。重要&gt;:。

问题

但是,当你通过Python中的add_widget创建FancyButton时,imp:root是如何工作的?

现在当我按下按钮&#34;添加花式&#34;我收到错误:

  

文件&#34; main.py&#34;,第18行,在AddFancy中        temp = Factory.FancyButton(text =&#39; f&#39;,imp = self.ids.imp)      文件&#34; properties.pyx&#34;,第756行,在kivy.properties.ObservableDict .__ getattr __(kivy / properties.c:11093)    AttributeError:&#39; super&#39;对象没有属性&#39; __ getattr __&#39;

跟进问题

Kivy outside rule inherence 2

1 个答案:

答案 0 :(得分:1)

Widget.ids仅包含其子级的ID http://kivy.org/docs/api-kivy.uix.widget.html#kivy.uix.widget.Widget.ids。小部件本身的ID不需要,因为您可以直接传递它 - 在您的情况下使用self ,因为您从方法内部传递了对窗口小部件的引用:

class Important(StackLayout):
    def NoInspiration(self, smile):
        print("Received: {}".format(smile))

    def AddFancy(self):
        print(self.ids) # only returns {'boxy': <weakproxy at 0000000002D119A8 to BoxLayout at 0000000002D026A8>}
        self.ids.boxy.add_widget(FancyButton(text='f', imp = self)) # no need to use a factory