python - Must Kivy properties be used in all classes? -
classic common-sense programming says separate gui code core processing. started way in kivy, ran problem in first-round prototype.
deck.py
class card: def __init__(self, suit, value): self.name = "%s %s" % (suit, value)
main.py
from kivy.app import app kivy.uix.boxlayout import boxlayout kivy.properties import objectproperty deck import card class carddisplay(boxlayout): card = objectproperty(card("default", 0)) class boarddisplay(boxlayout): board = [[card("player1", 1), card("player1", 2), card("player1", 3), card("player1", 4)], [card("player2", 1), card("player2", 2), card("player2", 3), card("player2", 4)]] class gameapp(app): pass if __name__ in ("__main__", "__android__"): gameapp().run()
game.kv
boarddisplay: orientation: "vertical" boxlayout: carddisplay: card: root.board[0][0] carddisplay: card: root.board[0][1] carddisplay: card: root.board[0][2] carddisplay: card: root.board[0][3] boxlayout: carddisplay: card: root.board[1][0] carddisplay: card: root.board[1][1] carddisplay: card: root.board[1][2] carddisplay: card: root.board[1][3] <carddisplay>: label: text: root.card.name
running this, 8-card display expected, of cards "default 0". think because using root.card.name, not stringproperty, attribute of card class. however... better way this? supposed inherit widget (or it) in every class contains i'll want display (in case, card)? or there binding method failing understand? read through kivy docs , swear mentioned problem this, wasn't able find reference again...
the problem root.card.name
isn't property
, when assign (text: root.card.name
) kivy doesn't know bind anything. binding happens automatically in kv, it's not perfect. here's easy fix:
<carddisplay>: label: text: root.card , root.card.name
the result of expression root.card , root.card.name
value of root.card.name
, assuming root.card
assigned. when kivy reads assignment, sees using root.card
, bind appropriately.
the key using properties knowing when want notified updates. don't need root.card.name
stringproperty
unless want know when property updated. in other words, if change card
instance used carddisplay
, update label
. however, if update name
attribute of card
, label
not update.
however, applies equally board
attribute on boarddisplay
. updating attribute not update display, since board
isn't property. kivy can handle lists of lists , provide notifications on updates:
board1 = listproperty([card("player1", i) in range(4)]) board2 = listproperty([card("player2", i) in range(4)]) board = referencelistproperty(board1, board2)
this way notifications around.
oh, 1 thing forgot mention: if need use properties on non-widget
(like card
), can extend eventdispatcher
properties work. kivy isn't ui, it's framework. it's ok use kivy in non-ui code. if have used data binding in .net, can think of widget
control
or uielement
, eventdispatcher
dependencyobject
.
Comments
Post a Comment