Search code examples
pythonpython-3.xkivykivy-language

How to only do add_widget once in Kivy


I have a dynamic Screen which is generated based on a button you clicked on another screen. Issue is dat every time I enter the Screen, the buttons are regenerated and added to the existing buttons.

The reason is that I use the on_enter method, but I don't know how I can use on_kv_post for example, as these events happen on starting the app.

How can I initialise the screen every time I return to this screen?

class ClientEnvsGrid(Screen):
    envProp = StringProperty('')

    def __init__(self, **kwargs):
        super(ClientEnvsGrid, self).__init__(**kwargs)


    def on_enter(self, *args):
        clientProp = self.manager.get_screen('clientlist').clientProp

        try:
            client_filepath = os.path.join('clients', clientProp, "environments.json")
            client_file = open(client_filepath)

            clientdata = json.loads(client_file.read())

            print(clientdata)

            self.ids.clientlabel.text = clientdata["clientname"]

            for envs in clientdata["environments"]:
                print(envs["name"])
                envbutton = Button(text=envs["name"])
                envbutton.bind(on_press=lambda *args: self.pressed('envbtn', *args))
                self.ids.environments.add_widget(envbutton)
        except:
            print("No client data found")
            self.manager.current = 'clientlist'


    def pressed(self, instance, *args):
        self.envProp = args[0].text

Solution

  • I've managed to fix it to include clear_widgets in the environments GridLayout in the on_leave event.

    def on_leave(self, *args):
        self.ids.environments.clear_widgets()