Kivy Widget 不接受属性和命令

Kivy Widget does not accepts properties and commands

我想制作我的第一个 Kivy 游戏,敌人 运行 在屏幕上,玩家应该通过点击敌人来杀死他们。 我创建了一个敌人 class,它是关卡 class 的一部分,两者都是 class 小部件的子 class。我做了一个函数,它会自动将 class Enemy 的实例添加到 class 级别。我在 class Enemy 中做了一个 if 循环,它应该检查敌人是否到达了屏幕的尽头。 然后它应该从变量 zicie 中删除一个数字,然后它应该删除敌人,但两者都不起作用。

错误信息是:

   File "bbgsa1.py", line 47, in Update
     self.parent.remove_widget(self)
 AttributeError: 'NoneType' object has no attribute 'remove_widget'

   File "bbgsa1.py", line 45, in Update
     self.parent.zicie = self.parent.zicie - 1
 AttributeError: 'NoneType' object has no attribute 'zicie'

这是代码中有错误的部分:

class level(Widget):
    zicie = NumericProperty(10)# the variable containg the life of the player
    zloto = NumericProperty(0)
    e_killed = NumericProperty(0)
    intv1 = NumericProperty(2/1.)
    def __init__(self, **kwargs):
        super(level, self).__init__(**kwargs)
        Clock.schedule_interval(self.Update, self.intv1)
    def Update(self, *args):# this funktion generates enemys
        obj = ROOT.ids.place.ids.level
        obj.add_widget(Enemy(pos=(800,100))) # the widget enemy is added here

class Enemy(Widget):
    imgp = StringProperty('enemy.png')
    velocity = NumericProperty(1)
    intv = NumericProperty(0/60.)
    def __init__(self, **kwargs):
        super(Enemy, self).__init__(**kwargs)
        Clock.schedule_interval(self.Update, self.intv)

    def Update(self, *args):# the funktion that lets the enemy move
        self.x -= self.velocity
        if self.x < 1:# checks if the enemy widget reached the end
            self.velocity = 0#m akes the enemy stop moving
            self.parent.zicie = self.parent.zicie - 1# the variable zicie that is not found
            self.parent.remove_widget(self) # this command is also not working

    def on_touch_down(self, touch):# the funktion, that lets the enemy die
        if self.collide_point(*touch.pos):
            self.velocity = 0
            self.imgp = 'enemyd.png'
            self.parent.e_killed += 1
            self.parent.zloto += 10
            self.parent.remove_widget(self)

这些错误是因为 self.parent 在行 运行 处是 None。我没有详细检查,但可能出现这种情况的一种方式是,即使在 Enemy 已从其父对象中删除后,也会调用 Clock scheduled self.Update 函数。

在敌人从屏幕上移除后,您应该小心地取消计划功能(以避免增加计划功能的数量),但也可以通过检查 self.parent 是否是直接解决问题None 在尝试根据其值做事之前。