我的self.canvas.clear()函数无法运行,但是方法中的其他代码运行

时间:2018-08-20 00:21:00

标签: python kivy

这是.kv字符串:

Builder.load_string('''
<Paint>:
     Button:
         text: 'clear'
         on_release: app.instance.cleaner()

''')

这是课程

class Paint(Widget):
    def cleaner(self, *args):
        self.canvas.clear()
        print('Cleared')

当单击按钮时,print('Cleared')可以完美打印,但是self.canvas.clear()不能执行任何操作

class MainApppp(App):
    def build(self):
        self.instance = Paint()
        return Background()

1 个答案:

答案 0 :(得分:1)

在下面的示例中,它说明了如何使用canvas.clear()函数来擦除小部件。

示例

main.py

from kivy.app import App
from kivy.uix.widget import Widget
from kivy.uix.boxlayout import BoxLayout
from kivy.lang import Builder

kv_string = '''
<Paint>:
    Button:
        text: 'clear'
        on_release: 
            # root.cleaner()
            app.root.erase()

<MyWidget>:
    canvas:
        Color:
            rgb: 0.1, 0.6, 0.3
        Ellipse:
            size: self.size     
            pos: self.pos

        Color:
            rgb: 0.6, 0.2, 0.1
        Ellipse:
            size: self.size     
            pos: self.center

<Background>:
    MyWidget:
        id: mywidget

    Paint:
        id: btn
'''

Builder.load_string(kv_string)


class Paint(Widget):

    def cleaner(self, *args):
        self.canvas.clear()
        print('Cleared')


class MyWidget(Widget):
    pass


class Background(BoxLayout):

    def erase(self):
        self.ids.mywidget.canvas.clear()


class TestApp(App):
    title = "Kivy Widget's canvas.clear() Demo"

    def build(self):
        return Background()


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

输出

Img01 - App Startup Img02 - Eclipse erased