释放动作到一个kivy按钮

我试图重构最后一个代码示例,以便Button实际上是具有on_release操作的自己的类。 但是我的代码失败了。

我不仅要重构它(每次我的尝试),而且还需要将Button的文本设置为“清除”

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):
        userdata = touch.ud
        userdata['color'] = c = (random(), 1, 1)
        with self.canvas:
            Color(*c, mode='hsv')
            d = 30
            Ellipse(pos=(touch.x - d/2, touch.y - d/2), size=(d, d))
            userdata['line'] = Line(points=(touch.x, touch.y))

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

class ClearButton(Button):
    def __init__(self, paint_widget):
        self.paint_widget=paint_widget

    def on_release(self, button):
        self.paint_widget.canvas.clear()

class MyPaintApp(App):

    def build(self):
        parent = Widget()
        painter = MyPaintWidget()
        clearbtn = ClearButton(painter)
        parent.add_widget(painter)
        parent.add_widget(clearbtn)

        return parent


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



没有子类,你可以做:

class MyPaintWidget(Widget):
    # ... put your previous methods here
    def clear_canvas(self, *largs):
    self.canvas.clear()

class MyPaintApp(App):
    def build(self):
    root = FloatLayout()
    painter = MyPaintWidget()
    cleanbtn.bind(on_release=self.painter.clear_canvas)
    root.add_widget(painter)
    root.add_widget(clearbtn)
    return root

通过继承,我宁愿选择Kv语言:

from kivy.lang import Builder

Builder.load_string('''
<ClearButton>:
    text: "Clear"
    on_release: app.painter.canvas.clear()
''')

class ClearButton(Button):
    pass

class MyPaintApp(App):

    def build(self):
    parent = Widget()
    painter = MyPaintWidget()
    clearbtn = ClearButton()
    parent.add_widget(painter)
    parent.add_widget(clearbtn)
    return parent
链接地址: http://www.djcxy.com/p/56451.html

上一篇: release action to a kivy button

下一篇: What is the best way to manage db connection in a preforking daemon