python - 动态改变矩形颜色
问题描述
在下面的示例中,在 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=...)
在这种情况下可能有什么解决方案?
解决方案
您可以更改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()
推荐阅读
- java - Apache骆驼:停止交换继续删除=真
- c# - 将下拉列表值从视图传递到控制器
- python - BeautifulSoup4 不能只从标签中提取文本
- c# - 为什么我们需要在 azure 数据工厂中进行 ML 批量执行和更新资源选项
- c# - Convert.ToBase64String 为字节 [] 抛出“System.OutOfMemoryException”(文件:大尺寸)
- qt - Qt TCP 服务器在单独的线程中运行 readyRead()
- python-3.x - Python请求图像上传返回错误500但curl命令有效
- umbraco - Umbraco 7 - 指向另一个网站内受保护页面的链接第一次重定向到 ROOT 页面
- php - 编辑 Laravel 插件
- python - 使用来自另一个 DataFrame 的值有效地将列添加到 Pandas DataFrame