2017-11-04 68 views
1

我在測試Kivy v1.10.0,並不明白爲什麼我設置Kivy屬性的位置有所不同。爲什麼在使用bind()時init()中聲明的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() 

但是,如果我替換目前線路在類級別:由等值CustomBtn.__init__()

pressed = ListProperty([0, 0]) 

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有所不同?

回答

1

我相信聲明(分配)在類層次的一個屬性的任何 方法和在__init__()做同樣是相等的。

沒有。 Kivy的屬性 - 描述符(way it works)。描述符對象should be存儲在課堂上工作。這是Python的東西 - 沒有Kivy特有的。

+0

我評論了一個關於鏈接問題的答案(我之前做過,但後來忘記了):一個描述符的實例屬性將被重新分配給賦值的類型(例如'self.pressed = touch .pos'丟棄描述符並將'pressed'按鈕反彈到'pos')。 – mins

+0

如果你試着看,不會,因爲類管理它的屬性設置,如果它是錯誤的類型,它將不會接受新的值。 – Tshirtman

相關問題