首页 > 解决方案 > 如何根据 if 语句改变画布的颜色?

问题描述

我正在尝试根据 main.py 中编写的 if 语句更改我的 kv 文件中画布的颜色。

这是我的 kv 文件的示例;

<BeltStatusScreen>
    FloatLayout:
        canvas:
            Color:
                rgb: utils.get_color_from_hex("#306998")
            Rectangle:
                size: self.size
                pos: self.pos
            Color:
                rgba: 1, 1, 1, 1
            Line:
                width: 4.
                circle:
                    (self.center_x, self.center_y, min(self.width - 200, self.height - 400)
                    / 2)
            Color:
                rgba: 1, 1, 1, 1
                id: sensor_one
            Ellipse:
                pos: 750, 155
                size: 100, 100

这是 main.py 中的 if 函数

    def current_status(self):
        address = "##########"
        w_characteristic = '##########'
        r_characteristic = '##########'

        async def connect(address):
            async with BleakClient(address, loop=loop) as client:
                await client.get_services()
                value = await client.read_gatt_char(r_characteristic)
                if await client.read_gatt_char(r_characteristic) == bytearray(b'\x03'):
                    self.root.ids['belt_status_screen'].ids['sensor_one'].background_color = (1, 0, 0, 1)
                    
        loop = asyncio.get_event_loop()
        loop.run_until_complete(connect(address))

我要么没有得到回复意味着没有颜色变化,所以为了测试它,我创建了一个按钮来直接调用该函数,但是在多次调用此函数后,我收到以下错误:

self.root.ids['belt_status_screen'].ids['sensor_one'].background_color = (1, 0, 0, 1)
 KeyError: 'sensor_one'

我将如何解决这个问题,或者我如何能够保持这个 while 循环运行并更改 kv 文件中的颜色?目的是成为传感器如何响应的实时镜像。因此,您可以随时进入该屏幕并监控传感器。任何帮助是极大的赞赏!

标签: pythonkivy

解决方案


推荐阅读