Kivy 外部规则继承 [英] Kivy outside rule inherence

查看:15
本文介绍了Kivy 外部规则继承的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

I want to specify a special button so I don't have to adjust every button I use, however I want it's event to trigger a function in a different class.

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 (working)

#:kivy 1.9.0

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


<Important>:
    id: imp

    FancyButton:
        text: "smiley"

BoxLayout:
    Important

Received: :)

test.kv (not working)

#:kivy 1.9.0

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


<Important>:
    id: imp

    BoxLayout:
        FancyButton:
            text: "smiley"

BoxLayout:
    Important

In the 2nd test.kv I added 'BoxLayout:' in front of FancyButton and suddenly I get the error:

AttributeError: 'BoxLayout' object has no attribute 'NoInspiration'

Question

  • Why does self.parent only refer to the direct parent and not < Important > in the 2nd example?
  • How can I have on_release: in < FancyButton > point to the function NoInspiration() while keeping the function in < Important >?

Follow up questions

解决方案

Change the kv to this

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


<Important>:
    id: imp

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

BoxLayout:
    Important

这篇关于Kivy 外部规则继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆