首页 > 解决方案 > 动态改变矩形颜色

问题描述

在下面的示例中,在 FloatLayout 的画布中绘制了两个矩形。

目标是创建一个简单的像素艺术绘图应用程序,用户可以在其中绘制矩形并更改其颜色(例如鼠标下矩形的颜色),因此我无法在 kv 文件中创建这些矩形。

所以在这个演示示例中,我只想更改鼠标下矩形的颜色。

from kivy.app import App
from kivy.lang import Builder
from kivy.properties import ListProperty
from kivy.graphics import Color, Rectangle

KV = """
FloatLayout
    size_hint: None, None
    size: 512, 512
    on_touch_down: app.test(*args[1].pos)
"""


class MyApp(App):

    color = ListProperty((1,1,1,1))

    def build(self):
        self.root = Builder.load_string(KV)

        self.init_rects()

    def init_rects(self):
        with self.root.canvas:
            x,y = self.root.pos
            w,h = self.root.size

            Color(rgba=(1,1,1,1))
            self.r1 = Rectangle(pos = (x,y), size= (w/2,h))
            Color(rgba=(1,0,0,1))
            self.r2 = Rectangle(pos = (w/2,y), size= (w/2,h))

    def test(self, x,y):
        if x< self.root.center_x:
            print ('I need to color this rectangle (self.r1) to red')
        else:
            print ('I need to color this rectangle (self.r2) to white')

MyApp().run()

在此示例中,我将矩形存储为 self.r1 和 self.r2(因为我认为我需要进一步更改它们的位置或大小)

问题是我没有找到如何仅更改一种矩形颜色而不更改其他颜色的示例。

我有一个愚蠢的解决方案(如下) - 每次都创建一个新矩形。但我确信当会有很多矩形时,这是一个糟糕的解决方案

    def test(self, touch_x, touch_y):
        with self.root.canvas:

            x,y = self.root.pos
            w,h = self.root.size

            if touch_x< self.root.center_x:
                Color(rgba=(1,0,0,1))
                self.r1 = Rectangle(pos = (x,y), size= (w/2,h))
            else:
                Color(rgba=(1,1,1,1))
                self.r2 = Rectangle(pos = (w/2,y), size= (w/2,h))

粗略地说,我想念类似的东西Rectangle(rgba=...)

在这种情况下可能有什么解决方案?

标签: pythonkivy

解决方案


您可以更改Color而不是尝试更改Rectangle. 这是对您的代码的修改,它演示了这一点:

from kivy.app import App
from kivy.lang import Builder
from kivy.properties import ListProperty
from kivy.graphics import Color, Rectangle

KV = """
FloatLayout
    size_hint: None, None
    size: 512, 512
    on_touch_down: app.test(*args[1].pos)
"""


class MyApp(App):

    color = ListProperty((1,1,1,1))

    def build(self):
        self.root = Builder.load_string(KV)

        self.init_rects()

    def init_rects(self):
        with self.root.canvas:
            x,y = self.root.pos
            w,h = self.root.size

            self.c1 = Color(rgba=(1,1,1,1))
            Rectangle(pos = (x,y), size= (w/2,h))
            self.c2 = Color(rgba=(1,0,0,1))
            Rectangle(pos = (w/2,y), size= (w/2,h))

    def test(self, x,y):
        if x< self.root.center_x:
            print ('I need to color this rectangle (self.r1) to red')
            self.c1.rgba = (1,0,0,1)
        else:
            print ('I need to color this rectangle (self.r2) to white')
            self.c2.rgba = (1,1,1,1)

MyApp().run()

推荐阅读