gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 02:38:55 24 4
gpt4 key购买 nike

我正在测试 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 特有的东西。

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com