我的简化.kv文件:
<GameWorld>:
player: the_player
canvas:
Rectangle:
pos: 5, root.top - 25
size: self.player.health, 20 # error raised in this line
Player:
id: the_player
center: self.center我的简化Python文件:
class Player(Widget):
health = NumericProperty(50)
def __init__(self, **kwargs):
super(Player, self).__init__(**kwargs)
self.health = 100
class GameWorld(Widget):
player = ObjectProperty()
entities = ListProperty()
def __init__(self, **kwargs):
super(GameWorld, self).__init__(**kwargs)
self.entities.append(self.player)我得到的错误是:
AttributeError: 'NoneType' object has no attribute 'health'基维认为self.player是None。请帮我弄明白出了什么问题。
发布于 2016-04-28 11:17:46
在评估canvas指令时,GameWorld.player仍然是None,这是ObjectProperty的默认值,因此出现错误。
如果您将None测试添加到kv规则中,如下所示:
<GameWorld>:
player: the_player
canvas:
Rectangle:
pos: 5, root.top - 25
size: self.player is not None and self.player.health, 20不会抛出错误,但不会执行自动绑定。但是,如果将rebind=True添加到ObjectProperty的声明中
class GameWorld(Widget):
player = ObjectProperty(rebind=True)这将正常工作。
留下不太优雅的替代解决方案:
您可以在定义时实例化一个Player对象:
class GameWorld(Widget):
player = ObjectProperty(Player())或者,您可以将另一个NumericProperty添加到GameWorld,唯一的目的是绑定到player.health,但初始化为合理的值:
class GameWorld(Widget):
_player_health = NumericProperty(1)和
<GameWorld>:
player: the_player
_player_health: the_player.health
canvas:
Rectangle:
pos: 5, root.top - 25
size: self._player_health, 20https://stackoverflow.com/questions/36904093
复制相似问题