基本上,我有一个带正方形的网格,我跟踪每个正方形上布满了BooleanProperty的正方形。这是我的代码中所有地方的简化版本我宣布"占用"属性:
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 :(得分:2)
请注意,对于属性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()