我正在测试Kivy v1.10.0,但不明白为什么我设置Kivy属性的位置会有所不同。

此代码有效:

from kivy.app import App
from kivy.properties import ListProperty
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.widget import Widget


class CustomBtn(Widget):
    pressed = ListProperty([0, 0])

    def __init__(self, **kwargs):
        super(CustomBtn, self).__init__(**kwargs)
        # self.pressed = ListProperty([0, 0])

    def on_touch_down(self, touch):
        if self.collide_point(*touch.pos):
            self.pressed = touch.pos
            return True
        return super(CustomBtn, self).on_touch_down(touch)


class RootWidget(BoxLayout):
    def __init__(self, **kwargs):
        super(RootWidget, self).__init__(**kwargs)
        cb = CustomBtn()
        self.add_widget(cb)
        cb.bind(pressed=self.btn_pressed)

    def btn_pressed(self, instance, pos):
        print(pos)


class MyApp(App):
    def build(self):
        return RootWidget()


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


但是,如果我替换当前在课程级别的行:

pressed = ListProperty([0, 0])


CustomBtn.__init__()中的等效项:

self.pressed = ListProperty([0, 0])


我在指令cb.bind(pressed=self.btn_pressed)中收到错误:

File "kivy\_event.pyx", line 438, in kivy._event.EventDispatcher.bind (kivy\_event.c:6500)
KeyError: 'pressed'


我相信在任何方法中在类级别声明(分配)属性,并在__init__()中进行相同操作。 Kivy属性不是Python属性,也许构建对象的顺序不同,并且对Kivy有影响吗?

最佳答案

我相信在任何一个类级别上声明(分配)一个属性
  方法和__init__()中的相同操作是等效的。


不。 Kivy的属性-是描述符(way it works)。描述符对象should be存储在类中即可工作。这是Python的东西-没有特定于Kivy的东西。

关于python - 为什么在使用bind()时在init()中声明的Kivy属性会生成错误?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/47107118/

10-09 06:30
查看更多