2016-02-10 121 views
0

本質上,我有一個正方形的網格,並且我跟蹤每個正方形上的布爾屬性佔據了哪些方塊。下面是我的代碼的所有地方的簡化版本,我宣佈「佔領」屬性:Kivy綁定on_property似乎並不工作

class Board(GridLayout): 
    def __init__(self): 
     super().__init__() 
     self.cols = 4 
     self.grid = [] 
     self.create_slots() 




    def create_slots(self): 
     for i in range(10): 
      self.grid.append([]) 
      for j in range(4): 
       temp = Square(i,j, "sideboard") 
       self.grid[i].append(temp) 
       self.add_widget(temp) 
       temp.bind(on_occupied = self.do_a_thing) 


    def do_a_thing(self): 
     for square in self.children: 
      #do a thing 

class Square(Button): 
    def __init__(self, row, col, type): 
     self.row = row 
     self.col = col 
     self.id = str(self.row) + "," + str(self.col) 
     self.type = type 
     self.occupied = BooleanProperty(False) 
     super().__init__() 

我的目標是結合了「do_a_thing」的方法每次被稱爲廣場的「佔領」屬性的值變化。由於Square類在我的應用程序的其他地方使用,我不想在kivy語言中爲on_occupied設置回調,並且我希望避免創建Square子類來更改一個綁定。

當我運行我的代碼時,它不會引發任何錯誤,並且我已驗證「佔用」屬性確實發生了更改。但「do_a_thing」方法永遠不會被解僱。誰能告訴我我做錯了什麼?

+0

綁定到'occupied'(我已經犯了那個錯誤之前) – zeeMonkeez

+0

嗯,@zeeMonkeez,我試過了,但我發現了這個錯誤:文件「kivy/_event.pyx」,第438行,在kivy._event.EventDispatcher.bind(kivy/_event.c:6026) KeyError:'occupied' – KSully2

+0

另外,請確保你'self.add_widget(Square()) '(Square的實例而不是類)。最後,'do_a_thing'應該有3個參數。 – zeeMonkeez

回答

1

請注意,對於屬性my_property,更改事件也稱爲my_property。該回調接收兩個參數:instance that fired the event, and new value of the property,如the docs所示。此外,如果該類有一個稱爲on_propertyname的方法,則也會調用該方法。 這裏是一個自包含的例子,對我的作品:

from kivy.app import App 
from kivy.lang import Builder 
from kivy.uix.gridlayout import GridLayout 
from kivy.uix.button import Button 
from kivy.properties import BooleanProperty 

class Board(GridLayout): 
    def __init__(self, **kwargs): 
     super(Board, self).__init__(**kwargs) 
     for i in range(10): 
      self.add_widget(Square()) 
     for square in self.children: 
      print square 
      square.bind(occupied=self.do_a_thing) 

    def do_a_thing(self, *args): 
     print "hello from {}, new state: {}".format(*args) 
     for square in self.children: 
      pass 
      #do a thing 

class Square(Button): 
    occupied = BooleanProperty(False) 
    def on_occupied(self, *args): 
     print "Callback defined in class: from {} state {}".format(*args) 


class mApp(App): 
    def build(self): 
     return Builder.load_string(""" 
Board: 
    cols: 4 
    rows: 3 
<Square>: 
    on_press: self.occupied = ~self.occupied 
""") 
mApp().run() 
+0

感謝您花時間幫助我。我已經按照你的建議編輯了我的代碼,即使使用你的確切的on_occupied方法。然而,當我綁定到「佔用」,我仍然得到一個KeyError(在kivy._event.EventDispatcher.bind(kivy/_event.c:6026)KeyError:'佔用')。如果我嘗試綁定到「on_occupied」(這當然不起作用),這不會發生。 – KSully2

+0

@ KSully2這個例子是否按原樣運行? – zeeMonkeez

+0

是的,你的例子運行良好。我已經在原始問題中編輯了我的代碼,因爲錯誤沒有發生在簡單的代碼片段中。 – KSully2