Search code examples
pythonkivykivy-language

Kivy - How do I set my app to be resizable up to a specified size?


How do I set my Kivy app to be resizable up to a specified size and no bigger than specified size but can be resized smaller than specified size?


Solution

  • This is quite simple to implement, but I'm afraid you can't do it in "realtime" (at least not on Windows), because the size property is updated after you release the button from resizing i.e. "confirm" the final size. For that you'd need to get to WinAPI and other appropriate system APIs, but beware it'll be really resource hungry as with the system API you'd basically check for every change (even 300 → 300.0000000001 if the window manager would allow floats).

    That being said, with Kivy you can make it quite easily when the behavior has to check for resizing and forbid actually making it bigger without disabling the Window's resizing in any way.

    You'll need to set the initial size first though (with Config before any other Kivy import) to make it consistent, otherwise you'll end up with a Window of size 800x600 and after you attempt to resize, then it'll scale down to 300x150. The rest is just about a binding to either size or on_resize attributes of the Window

    # set the initial size
    from kivy.config import Config
    
    MAX_SIZE = (300, 150)
    Config.set('graphics', 'width', MAX_SIZE[0])
    Config.set('graphics', 'height', MAX_SIZE[1])
    
    from kivy.app import App
    from kivy.uix.button import Button
    from kivy.core.window import Window
    
    
    class My(App):
        def check_resize(self, instance, x, y):
            # resize X
            if x > MAX_SIZE[0]:
                Window.size = (300, Window.size[1])
            # resize Y
            if y > MAX_SIZE[1]:
                Window.size = (Window.size[0], 150)
    
        def build(self):
            Window.bind(on_resize=self.check_resize)
            return Button()
    
    My().run()