Skip to main content
 首页 » 编程设计

python之为什么我在 .kv 文件中得到 `' NoneType' object has no attribute`

2025年04月02日16pander-it

我简化的 .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' 

Kivy 认为 self.player 是 None。请帮助我了解问题所在。

请您参考如下方法:

当 canvas 指令被评估时,GameWorld.player 仍然是 None,ObjectProperty 的默认值,因此错误。

如果像这样向 kv 规则添加针对 None 的测试:

<GameWorld>: 
    player: the_player 
    canvas: 
        Rectangle: 
            pos: 5, root.top - 25 
            size: self.player is not None and self.player.health, 20 

不会抛出任何错误,但不会执行自动绑定(bind)。但是,如果您添加 rebind=True到 ObjectProperty 的声明:

class GameWorld(Widget): 
    player = ObjectProperty(rebind=True) 

这将正常工作。


留下不太优雅的替代解决方案:

您可以在定义时实例化一个 Player 对象:

class GameWorld(Widget): 
    player = ObjectProperty(Player()) 

或者,您可以将另一个 NumericProperty 添加到 GameWorld,其唯一目的是绑定(bind)到 player.health,但初始化为合理的值(value):

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, 20