Kivy外面统治固有

时间:2015-07-24 19:41:25

标签: python kivy

我想指定一个特殊的按钮,所以我不必调整我使用的每个按钮,但是我希望它能在不同的类中触发一个函数。

main.py

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


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


class Important(StackLayout):

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


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

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

test.kv(工作)

#:kivy 1.9.0

<FancyButton@Button>:
    on_release: self.parent.NoInspiration(':)')


<Important>:
    id: imp

    FancyButton:
        text: "smiley"

BoxLayout:
    Important
  

收到:: :)

test.kv(正在工作)

#:kivy 1.9.0

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


<Important>:
    id: imp

    BoxLayout:
        FancyButton:
            text: "smiley"

BoxLayout:
    Important

在第二次测试中,我添加了BoxLayout:&#39;在FancyButton面前突然我得到错误:

  

AttributeError:&#39; BoxLayout&#39;对象没有属性&#39; NoInspiration&#39;

问题

  • 为什么self.parent仅引用直接父级而不是&lt;重要&gt;在第二个例子中?
  • 我如何拥有on_release:in&lt; FancyButton&gt;指向函数NoInspiration(),同时保持函数在&lt;重要&gt;?

跟进问题

1 个答案:

答案 0 :(得分:1)

将kv更改为此

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


<Important>:
    id: imp

    BoxLayout:
        FancyButton:
            text: "smiley"
            imp: root

BoxLayout:
    Important