Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

To alternate between .kv files for closing one window and opening another in Kivy, you can follow the below steps:

Step 1: Create a class for the first window and one for the second window.

Step 2: In the first window, create a button widget to switch to the second window.

Step 3: In the second window, create a button widget to switch back to the first window.

Step 4: Create two .kv files, one for each window, and define the structure and design of the windows in the .kv files.

Step 5: In the main Python file, you can load the appropriate .kv file for each window using the Builder.load_file function.

Step 6: On button press, you can use the App.getrunningapp().root function to switch between windows.

Here is an example code:

main.py file:

from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.lang import Builder

Builder.load_file('first_window.kv')
Builder.load_file('second_window.kv')


class FirstWindow(BoxLayout):
    def switch_windows(self):
        self.parent.parent.current = 'second'


class SecondWindow(BoxLayout):
    def switch_windows(self):
        self.parent.parent.current = 'first'


class WindowManager(BoxLayout):
    pass


class TestApp(App):
    def build(self):
        return WindowManager()


if __name__ == "__main__":
    TestApp().run()

first_window.kv file:

<FirstWindow>:
    orientation: 'vertical'
    Label:
        text: 'First Window'
    Button:
        text: 'Switch to Second Window'
        on_press: root.switch_windows()

<WindowManager>:
    id: window_manager
    orientation: 'vertical'
    ScreenManager:
        id: screen_manager
        screen: 'first'
        Screen:
            name: 'first'
            FirstWindow:
                id: first_window
        Screen:
            name: 'second'
            SecondWindow:
                id: second_window

second_window.kv file:

<SecondWindow>:
    orientation: 'vertical'
    Label:
        text: 'Second Window'
    Button:
        text: 'Switch to First Window'
        on_press: root.switch_windows()

In this example code, when the 'Switch to Second Window' button is pressed in the FirstWindow class, the 'switchwindows' method is called, which changes the current screen of the WindowManager class to the 'second' screen. Similarly, when the 'Switch to First Window' button is pressed in the SecondWindow class, the 'switchwindows' method is called, which changes the current screen back to the 'first' screen.