Search code examples
pythonkivy

Kivy image button stretching


I'm trying to make a button with an image. However the image is stretched out. Is there a way I can make it a "fixed position", so whenever the Resolution changes, it won't get stretched out (using python)?

self.add_widget(Button(background_normal=('Image.png'),size_hint_x=(0.5),size_hint_y=(0.3),pos_hint={"x":0.3, "top":0.7}))

Solution

  • There is another thing you can do here by using the Kivy Behaviors module.

    In your python file:

    from kivy.uix.behaviors import ButtonBehavior
    from kivy.uix.image import Image
    
    class ImageButton(ButtonBehavior, Image):
        pass
    
    self.add_widget(ImageButton(source=('Image.png'),size=(200,200), size_hint=(None,None),pos_hint={"x":0.3, "top":0.7}))
    

    The ImageButton can now access both Button properties (like the 'on_press' method) as well as Image properties (including 'keep_ratio' and allow_stretch) which default to True and False, which is what you want in this example.