本文介绍了使用add_widget()的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:

关注问题

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-27 00:00