3

我正在尝试重构最后一个代码示例,以便它Button实际上是它自己的带有on_release动作的类。但是我的代码失败了。

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

从随机导入随机
从 kivy.app 导入应用程序
从 kivy.uix.widget 导入小部件
从 kivy.uix.button 导入按钮
从 kivy.graphics 导入颜色、椭圆、线


MyPaintWidget 类(小部件):

    def on_touch_down(自我,触摸):
        用户数据 = touch.ud
        用户数据['color'] = c = (random(), 1, 1)
        使用 self.canvas:
            颜色(*c,模式='hsv')
            d = 30
            椭圆(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]

类清除按钮(按钮):
    def __init__(self,paint_widget):
        self.paint_widget=paint_widget

    def on_release(自我,按钮):
        self.paint_widget.canvas.clear()

MyPaintApp 类(应用程序):

    定义构建(自我):
        父 = 小部件()
        画家 = MyPaintWidget()
        clearbtn = ClearButton(画家)
        parent.add_widget(画家)
        parent.add_widget(clearbtn)

        返回父母


如果 __name__ == '__main__':
    MyPaintApp().run()


4

1 回答 1

8

如果没有子类化,你可以这样做:

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
于 2012-10-03T06:36:39.640 回答