kivy remove_widget 不工作

kivy remove_widget is not working

我想做一个火柴人游戏运行,点击它,火柴人就消失了。 我尝试使用 Place.remove_widget(Enemy) 删除敌人小部件,但程序崩溃了,我收到此错误消息:

TypeError: unbound method remove_widget() must be called with Place instance as first argument (got WidgetMetaclass instance instead)

这是我的源代码:

from kivy.app import App
from kivy.uix.button import Button
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.widget import Widget
from kivy.lang import Builder
from kivy.properties import NumericProperty
from kivy.clock import Clock
from kivy.animation import Animation

class Place(FloatLayout):
    pass
class Enemy(Widget):
    velocity = NumericProperty(1)
    def __init__(self, **kwargs):
        super(Enemy, self).__init__(**kwargs)
        Clock.schedule_interval(self.Update, 1/60.)
    def Update(self, *args):
        self.x -= self.velocity
        if self.x < 1:
            self.velocity = 0
    def on_touch_down(self, touch):
        if self.collide_point(*touch.pos):
            print 'es geht'
            self.velocity = 0
            Place.remove_widget(Enemy)


ROOT = Builder.load_string('''
Place:
    Button:
        text: 'Go Back'
        size_hint: 0.3, 0.1
        pos_hint: {"x": 0, 'y':0}
    Enemy:
        pos: 400, 100
<Enemy>:
    Image:
        pos: root.pos
        id: myimage
        source: 'enemy.png'

''')

class Caption(App):
    def build(self):
        return ROOT
if __name__ == '__main__':
    Caption().run()
Place.remove_widget(Enemy)

这就是问题所在 - 您不是要从 实例 中移除敌人 class 的 实例地方 class 的一部分,而是试图从另一个地方移除实际的 class 本身。这就是a = Placea = Place()之间的区别——前者是关于如何制作Place的说明,后者是一个实际的个体Place实例。

在这种情况下,您可能会这样做 self.parent.remove_widget(self); self.parent 是包含 Enemy 实例的 Place 实例。