How do I change the color of my widget in Kivy at run time?

前端 未结 2 374
太阳男子
太阳男子 2020-12-08 15:55

I\'m having trouble changing the color of a simple widget in Kivy. I can set the color when I create the widget, but I can\'t change it afterwards.

Here is the simpl

相关标签:
2条回答
  • 2020-12-08 16:04

    In your initial version, you were just missing the declaration of the property

    from kivy.properties import NumericProperty
    

    in the header and

    r = NumericProperty(0)
    

    just under class CircleWidget(Widget):

    also, you state that your kv file is named circletest.kv, but your app is named TestApp, so you should change one of them to make them coherent, or your kv file won't be found, but as you don't report any issue with that, i guess it's only a typo in the question. edit: just saw the Builder.load_file ok,

    cheers.

    0 讨论(0)
  • 2020-12-08 16:21

    The answer by tshirtman is correct, here is the explanation of what's going on.

    In your kv file when you set

    <CircleWidget>:
        canvas:
            Color:
                rgba: self.r, 1, 1, 1
            Ellipse:
                pos: self.pos
                size: self.size
    

    The line rgba: self.r, 1, 1, 1 tries to update the value of rgba whenever there is a change to the value of r. This is done implicitly in kv language by binding, which can be done on a kivy Property as it implements a Observer Pattern.

    The variable r in your code was updated but it's just a variable that doesn't provide any indication that it's value has changed and can not be bound to. If you notice your changes to pos work because pos is a ReferenceListProperty.

    General rule for programming in Kivy, if you want to change code depending on a property of a Widget/Object use a Kivy Property. It provides you the option to Observe Property changes and adjust your code accordingly either explicitly through bind/on_property_name events or implicitly through kv language as mentioned above.

    0 讨论(0)
提交回复
热议问题