'改变颜色'按钮Python Kivy

时间:2018-06-15 14:11:35

标签: python kivy

我正在尝试创建一个绘图应用。我使用Kivy Canvas定义了线条的颜色(默认为红色),任务是我需要一个按钮,例如' Green'这会将颜色变为绿色。我真的不知道该怎么做。

我尝试的是:

class PainterWidget(Widget):
    def on_touch_down(self, touch):

        with self.canvas:
            self.color = Color(1, 0, 0, 1)
            rad = 30
            Ellipse(pos = (touch.x, touch.y), size = (rad / 2, rad / 2))
            touch.ud['line'] = Line(points = (touch.x, touch.y), width = 15)

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

    def blue(self):

        with self.canvas:
            self.color = Color(0, 0, 1, 1)

class PaintApp(App):

    def build(self):
        parent = Widget()
        self.painter = PainterWidget()
        parent.add_widget(self.painter)

        parent.add_widget(Button(text='Blue', size=(50, 50), pos=(0, 480), on_press = PainterWidget.blue))


        return parent

但它不起作用。我尝试在PaintApp中创建类似PainterWidget.color = Color的颜色更改方法,但它也没有用。

1 个答案:

答案 0 :(得分:1)

添加ListProperty,paint_color并指定默认的红色。按下按钮时,将paint_color从红色变为蓝色。有关详细信息,请参阅以下示例。

实施例

main.py

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


class PainterWidget(Widget):
    paint_color = ListProperty([1, 0, 0, 1])

    def on_touch_down(self, touch):
        with self.canvas:
            Color(rgba=self.paint_color)
            rad = 30
            Ellipse(pos = (touch.x, touch.y), size = (rad / 2, rad / 2))
            touch.ud['line'] = Line(points = (touch.x, touch.y), width = 15)

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

    def blue(self, instance):
        self.paint_color = [0, 0, 1, 1]


class PaintApp(App):

    def build(self):
        parent = Widget()
        self.painter = PainterWidget()
        parent.add_widget(self.painter)

        parent.add_widget(Button(text='Blue', size=(50, 50), pos=(0, 480), on_press=self.painter.blue))

        return parent


if __name__ == "__main__":
    PaintApp().run()

输出

Img01 - Red and Blue colors