Search code examples
canvaskivykivy-language

Kivy-how can i make my canvas height smaller than the parent height


I have a stacklayout with a canvas and an image. my image has a size_hint of .1 and I want my canvas to have the same height as my image.

.kv file:

StackLayout:
    orientation: 'lr-tb'
    canvas:
        Color:
            rgba: 1,1,1,1
        Rectangle:
            pos: self.pos
            size: self.size
    Image:              
        size_hint_y: .1
        source: 'Images\login\cptbanner.jpg'
        allow_stretch: True
        keep_ratio: True

what can I do to get the desired effect?


Solution

  • A Kivy canvas is not a widget or the space in which you paint. It is only a set of instructions. You can´t resize it. I guess you want to resize the drawn rectangle. I'm not sure what the outcome is you expect, but you can resize the rectangle using the width and height attributes of the parent widget:

    from kivy.app import App
    from kivy.base import Builder
    from kivy.uix.boxlayout import BoxLayout
    
    
    Builder.load_string("""
    <MainWindow>:
        StackLayout:
            id : aa
            orientation: 'lr-tb'
    
            canvas:
                Color:
                    rgba: 1,1,1,1
                Rectangle:
                    pos: 0, self.height*0.9
                    size: self.width, self.height*0.1
    
            Image:
                id: im
                size_hint_y: 0.1
                source: 'Images\login\cptbanner.jpg'
                allow_stretch: True
                keep_ratio: True
    """)
    
    class MainWindow(BoxLayout):
        def __init__(self, **kwargs):
            super(MainWindow, self).__init__(**kwargs)
    
    class MyApp(App):
        def build(self):
            return MainWindow()
    
    if __name__ == '__main__':
        MyApp().run()
    

    Result:

    enter image description here