“更改颜色”按钮Python Kivy

2024-09-28 05:15:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试创建一个绘图应用程序。我用kivycanvas定义线条的颜色(默认为红色),任务是我需要一个按钮,例如'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=颜色,但不太管用。在


Tags: posself颜色ondefwithwidgetclass
1条回答
网友
1楼 · 发布于 2024-09-28 05:15:27

添加一个ListProperty,paint_color,并指定默认的红色。按下按钮后,将油漆颜色从红色变为蓝色。详情请参考下面的例子。在

示例

在主.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

相关问题 更多 >

    热门问题