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

问题描述

后续问题: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
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,所以它知道它应该在 < 中查找函数.重要>:.

In test.kv the function call in FancyButton to the function NoInspiration() works, because the FancyButton defined in the .kv has imp: root, so it knows it should look for the function in < Important >:.

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

However how does imp: root work when you create FancyButton through add_widget in Python?

现在当我按下添加花式"按钮时,我得到了错误:

Now when I press the button "add fancy" I get the error:

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

跟进问题

Kivy 外部规则继承 2

推荐答案

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

Widget.ids only contain ids of its children (http://kivy.org/docs/api-kivy.uix.widget.html#kivy.uix.widget.Widget.ids. Id of the widget itself it's not needed because you can just pass it directly - in your case using self, since you're passing a reference to a widget from inside of a method:

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

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

10-29 16:00