1

I want to have opportunity to change or delete rectangle in builder, but I get AttributeError. How can I fix it? I hope you help me

from kivy.app import App
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.image import Image
from kivy.lang import Builder
from kivy.core.window import Window
from kivy.graphics import Color, Rectangle
Builder.load_string('''
<RootWidget>
    FloatLayout:
        id: layout
        canvas.before:
            Rectangle:
                id: image
                size: (100, 180)
                pos: (223, 191)
                source:'image.gif'
''')
class RootWidget(FloatLayout):
    def __init__(self, **kwargs):
        super(RootWidget, self).__init__(**kwargs)
        self.ids.layout.remove_widget(self.ids.image)

class WindowApp(App):
    def build(self):
        return RootWidget()

if __name__ == '__main__':
    WindowApp().run()
pinkcat
  • 327
  • 4
  • 17
  • What is the final result you want to achieve? Maybe there is a more easy way to achieve it. – adn05 Nov 21 '19 at 15:10

1 Answers1

1

Unfortunately, you can't set the id of a canvas object. Here is a workaround: Consider you want to change the source attribute of your Rectangle. Set rectangle_image: "image.gif" in your FloatLayout, then set source: self.rectangle_image in your Rectangle. Now you can reference the FloatLayout by its id and change its rectangle_image variable, and it will automatically update the Rectangle's source attribute!

Erik
  • 1,196
  • 2
  • 9
  • 18
  • I can't believe that worked. :) It's been surprisingly hard to find a way in Kivy, to change a background declared in kv-lang. – John C Jun 29 '22 at 13:57