【问题标题】:Kivy Widget does not accepts properties and commandsKivy Widget 不接受属性和命令
【发布时间】:2015-05-05 01:12:20
【问题描述】:

我想制作我的第一款 Kivy 游戏,敌人在屏幕上奔跑,玩家应该通过点击来杀死敌人。 我创建了一个 Enemy 类,它是关卡类的一部分,它们都是 Widget 类的子类。我做了一个函数,它自动将类 Enemy 的实例添加到类级别。我在 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)

【问题讨论】:

    标签: python widget kivy


    【解决方案1】:

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

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

    【讨论】:

    • 我尝试使用 self.unschedule(self.Update) 取消计划,但没有成功
    • 好的,我明白了,我是个白痴XD谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-14
    • 1970-01-01
    • 1970-01-01
    • 2023-01-05
    相关资源
    最近更新 更多