如何删除布局的内容

时间:2017-11-15 10:54:10

标签: python kivy-language

我的脚本allovs通过鼠标绘制线条。我想删除Butoon Clear的最后一行。(并且有时会逐渐删除所有行)在堆栈溢出时我发现构造“self.ids.layout.remove_widget(self.ids.test)”我如何创建“self.ids.test”动态?我该如何为脚本修改此构造?谢谢。

from random import random
from kivy.app import App
from kivy.uix.widget import Widget
from kivy.uix.button import Button
from kivy.graphics import Color, Ellipse, Line


class MyPaintWidget(Widget):

    def on_touch_down(self, touch):
        color = (random(), 1, 1)
        with self.canvas:
            Color(*color, mode='hsv')
            touch.ud['line'] = Line(points=(touch.x, touch.y))

    def on_touch_move(self, touch):
        touch.ud['line'].points += [touch.x, touch.y]


class MyPaintApp(App):

    def build(self):
        parent = Widget()
        self.painter = MyPaintWidget()
        clearbtn = Button(text='Clear', pos=(50,50))
        clearbtn.bind(on_release=self.clear_canvas)

        parent.add_widget(self.painter)
        parent.add_widget(clearbtn)
        return parent

    def clear_canvas(self, obj):
        pass

if __name__ == '__main__':
    MyPaintApp().run()

1 个答案:

答案 0 :(得分:0)

当一个像Line这样的指令被添加到画布时会返回,然后一个可能的解决方案是将这些指令存储在一个列表中,然后通过画布的remove()方法将其删除:

class MyPaintWidget(Widget):
    def __init__(self, *args, **kwargs):
        Widget.__init__(self, *args, **kwargs)
        self.lines = []

    def on_touch_down(self, touch):
        color = (random(), 1, 1)
        with self.canvas:
            Color(*color, mode='hsv')
            l = Line(points=(touch.x, touch.y))
            touch.ud['line'] = l
            self.lines.append(l)

    def on_touch_move(self, touch):
        touch.ud['line'].points += [touch.x, touch.y]


class MyPaintApp(App):

    def build(self):
        parent = Widget()
        self.painter = MyPaintWidget()
        clearbtn = Button(text='Clear', pos=(50,50))
        clearbtn.bind(on_release=self.clear_canvas)
        parent.add_widget(self.painter)
        parent.add_widget(clearbtn)
        return parent

    def clear_canvas(self, obj):
        if len(self.painter.lines) != 0:
            self.painter.canvas.remove(self.painter.lines[-1])
            self.painter.lines = self.painter.lines[:-1]

if __name__ == '__main__':
    MyPaintApp().run()

如果要清除所有必须使用的说明self.painter.canvas.clear()