Skip to main content
 首页 » 编程设计

python之为什么在使用 bind() 时在 init() 中声明的 Kivy 属性会产生错误

2024年10月01日8xing901022

我正在测试 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 有影响?

请您参考如下方法:

I believe declaring (assigning) an attribute at class level out of any method and doing the same in __init__() were equivalent.

没有。 Kivy 的属性 - 是描述符(way it works)。描述符对象 should be存储在类里面工作。这是 Python 的东西——没有 Kivy 特有的东西。