【问题标题】:'Change Color' button Python Kivy“更改颜色”按钮 Python Kivy
【发布时间】:2018-06-15 14:11:34
【问题描述】:

我正在尝试创建一个绘图应用程序。我使用 Kivy Canvas 定义线条的颜色(默认为红色),任务是我需要一个按钮,例如“绿色”,它将颜色更改为绿色。我真的不知道该怎么做。

我尝试的是:

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 之类的操作,但它也不起作用。

【问题讨论】:

    标签: python kivy


    【解决方案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()
    

    输出

    【讨论】:

    • 感谢您的快速回复!我做到了,它仍然没有改变颜色
    • 添加一个名为paint_colorListProperty 并将其从红色更新为蓝色。请参考更新后的帖子。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-08-25
    • 1970-01-01
    • 2019-06-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多