动态改变矩形颜色

在下面的示例中,在 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(因为我认为我需要进一步更改它们的位置或大小)


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


我有一个愚蠢的解决方案(如下) - 每次都创建一个新的矩形。

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

在这种情况下,解决方案是什么?


白衣染霜花
浏览 147回答 1
1回答

胡子哥哥

您可以更改Color而不是尝试更改Rectangle. 这是对您的代码的修改,演示了这一点:from kivy.app import Appfrom kivy.lang import Builderfrom kivy.properties import ListPropertyfrom kivy.graphics import Color, RectangleKV = """FloatLayout&nbsp; &nbsp; size_hint: None, None&nbsp; &nbsp; size: 512, 512&nbsp; &nbsp; on_touch_down: app.test(*args[1].pos)"""class MyApp(App):&nbsp; &nbsp; color = ListProperty((1,1,1,1))&nbsp; &nbsp; def build(self):&nbsp; &nbsp; &nbsp; &nbsp; self.root = Builder.load_string(KV)&nbsp; &nbsp; &nbsp; &nbsp; self.init_rects()&nbsp; &nbsp; def init_rects(self):&nbsp; &nbsp; &nbsp; &nbsp; with self.root.canvas:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; x,y = self.root.pos&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; w,h = self.root.size&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; self.c1 = Color(rgba=(1,1,1,1))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Rectangle(pos = (x,y), size= (w/2,h))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; self.c2 = Color(rgba=(1,0,0,1))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Rectangle(pos = (w/2,y), size= (w/2,h))&nbsp; &nbsp; def test(self, x,y):&nbsp; &nbsp; &nbsp; &nbsp; if x< self.root.center_x:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; print ('I need to color this rectangle (self.r1) to red')&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; self.c1.rgba = (1,0,0,1)&nbsp; &nbsp; &nbsp; &nbsp; else:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; print ('I need to color this rectangle (self.r2) to white')&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; self.c2.rgba = (1,1,1,1)MyApp().run()
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python