如何使用 id: 在 Kivy 中更改 canvas 颜色?

How to change canvas colour in Kivy using id:?

环顾四周,似乎找不到任何关于通过引用 id: 在 Kivy 中更改 canvas 颜色的可靠信息。我的目标是为我的应用程序创建一个浅色和深色主题,用户可以在其中更改应用程序设置。这是我目前的 .kv 代码:

themescreen.kv

<ThemeScreen>:
    id: theme_canvas
    canvas:
        Color:
            rgb: utils.get_color_from_hex("#161D39")
        Rectangle:
            size: self.size
            pos: self.pos
    FloatLayout:
        RoundedButton:
            id: dark_theme
            text: "Dark"
            pos_hint:  {"top": .5, "center_x": .5}
            size_hint: .38, .08
            padding: 20, 20
            opacity: 1 if self.state == 'normal' else .5
            on_release:
                app.change_theme("#000523")
        RoundedButton:
            id: light_theme
            text: "Light"
            pos_hint:  {"top": .3, "center_x": .5}
            size_hint: .38, .08
            padding: 20, 20
            opacity: 1 if self.state == 'normal' else .5
            on_release:
                app.change_theme("#C4CCFF")

所以我想要做的是 运行 将我的十六进制颜色更改为适当主题的函数。下面是我的 .py 函数。

    def change_theme(self, theme):
        theme_canvas = self.root.ids["theme_screen"].ids["theme_canvas"]
        theme_canvas.rgb = utils.get_color_from_hex(theme)

我试过将 id: 放在不同的位置,我试过将 rgb 颜色完全放在 FloatLayout 区域,并在 canvas 中使用 self.color 等,然后调用那个 id: 相反。目前,使用此设置我收到错误: theme_canvas =self.root.ids["theme_screen"].ids["theme_canvas"] KeyError: 'theme_canvas' 而我从函数中删除 theme_canvas 已经很累了。

请问有什么办法可以吗?我只是想通过我的函数改变 rgb 颜色。请帮忙。

您的问题有替代解决方案

因为你的objective是改变主题而运行,你可以使用kivymd(一个materialkivy的设计库)

您可以在应用程序中使用它来调整主题class

#light theme

self.theme_cls.theme_style = "Light"
#Dark theme
self.theme_cls.theme_style = "Dark"

这里是这个案例的一个实现

from kivymd.app import MDApp
from kivy.lang import Builder

Kv="""

BoxLayout:
    Button:
        size_hint:(.1,.1)
        text:'Light theme'
        on_press:
            app.Light()
            
    Button:
        size_hint:(.1,.1)
        text:'Dark theme'
        on_press:
            app.Dark()
"""
class Main(MDApp):
    def build(self):
        
        return Builder.load_string(Kv)
            
                                        
    def Light(self):
        
        self.theme_cls.theme_style = "Light"
        return Builder.load_string(Kv)
        
    def Dark(self):
        
        self.theme_cls.theme_style = "Dark"
        return Builder.load_string(Kv)
        
Main().run()


默认情况下,kivymd 主题将设置为“Light”

您可以在以下位置找到有关 Kivymd 主题的更多信息 https://kivymd.readthedocs.io/en/latest/themes/theming/index.html