Restarting an app in kivy

4.4k Views Asked by At

I've written a simple game that I want to restart after a certain button is pressed (so that EVERYTHING goes back to where it was when the app was run). So the question is: what do I need to type into on_press to start Game() ance again?

class Game(Widget):
    (...)
    def but_add(self, player):
        self.add_widget(Button(text=player,
                               font_size=30,
                               center_x=self.width/2,
                               center_y=self.height/2,
                               size=(self.height, self.height*7/20),
                               background_normal='katana.jpg',
                               background_down='katana.jpg',
                               markup=True,
                               on_press= ???????? ))
    (...)

class Okiya(App):
    def build(self):    
        return Game()

if __name__ == "__main__":
    Okiya().run()
3

There are 3 best solutions below

2
On

You probably don't really want to restart the entire app, but just to reset its state. The mechanism of doing so is up to you, you're the one that knows what the initial state should look like; for instance, you could do on_press=self.reset_func and define the reset_func method to perform all these tasks.

You could also remove the widget and add a new instance, which will have the default properties.

0
On

I don't know exactly what it's worth but the following works for an app I'm doing:

Add the following method to your application class:

class Okiya(App):
    def restart(self):
        self.root.clear_widgets()
        self.stop()
        return Okiya().run()

Then call the method from a python file where you want to restart the app with:

App.get_running_app().restart()
0
On

Here is my test example

from kivy.app import App
from kivy.uix.button import Button
from kivy import platform

if platform == 'android':
    from jnius import autoclass

    Intent = autoclass("android.content.Intent")
    PythonActivity = autoclass("org.kivy.android.PythonActivity")
    System = autoclass("java.lang.System")


class RestartApp(App):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.screen = Button(text='Restart', on_release=self.restart)

    def build(self):
        return self.screen

    def restart(self, *args):
        if platform == 'android':
            activity = PythonActivity.mActivity
            intent = Intent(activity.getApplicationContext(), PythonActivity)
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK)
            activity.startActivity(intent)
            System.exit(0)
        else:
            self.screen.clear_widgets()
            self.stop()
            RestartApp().run()


RestartApp().run()