Search code examples
pythonpython-3.xkivykivy-language

How to change the screen size on button press in Kivy


I tried using Window.size (height,widht) and Config but it was not working with Screen Manager


Solution

  • Solution

    Add a method (on_enter or on_pre_enter) in each screen and use Window.size as shown in the following example.

    Example

    main.py

    from kivy.app import App
    from kivy.uix.screenmanager import ScreenManager, Screen
    from kivy.core.window import Window
    
    
    class MyScreenManager(ScreenManager):
        pass
    
    
    class Main(Screen):
        def on_pre_enter(self):
            Window.size = (900, 600)
    
    
    class Login(Screen):
        def on_pre_enter(self):
            Window.size = (400, 300)
    
        def check_password(self, instance, password):
            if password == "pwd":
                instance.current = "screen2"
    
    
    class Screen2(Screen):
        pass
    
    
    class TestApp(App):
        def build(self):
            return MyScreenManager()
    
    
    if __name__ == "__main__":
        TestApp().run()
    

    test.kv

    #:kivy 1.10.0
    
    <MyScreenManager>:
        Main:
        Login:
            id: login
        Screen2:
    
    <Main>:
        name: "main"
        BoxLayout:
            orientation: "horizontal"
            Label:
                text: "Hello"
            Button:
                text: "Go to Login Screen"
                on_press: root.manager.current = "screen1"
    <Login>:
        name: "screen1"
        GridLayout:
            size_hint: (0.5, 0.5)
            pos_hint: {"center_x": 0.5, "center_y": 0.6}
            rows: 3
            padding: 20
    
            Label:
                size_hint: (0.2, 0.2)
                text:"Password:"
                font_size: 30
                halign: "center"
                valign: "middle"
    
            TextInput:
                id: password
                size_hint: (0.2, 0.06)
                cursor_blink: True
                font_size: 20
                multiline: False
                password: True
    
            Button:
                text: "Continue"
                size_hint: (0.2, 0.08)
                on_release:
                    root.manager.ids.login.check_password(root.manager, password.text)
    
    <Screen2>:
        name: "screen2"
        BoxLayout:
            orientation: "horizontal"
            Label:
                text: "Hello"
            Button:
                text: "Go to screen 1"
                on_press: root.manager.current = "screen1"
    

    Output

    Img01 - App Startup Img02 - Login Screen