Nerd For Tech
Published in

Nerd For Tech

How to Create a Back Button in Kivy

I created a back button by first setting up an __init__ function in my App class and then having self.previous_screen that would hold the name of the previous screen. I used <Screen> in the .kv file to make this apply to all the screens. Then whenever I created a back button, I would reference app.previous_screen.

The main.py file:

from kivy.uix.screenmanager import Screen, ScreenManager
from kivy.app import App, Builder

Builder.load_file("medium.kv")

class Home(Screen):
pass
class User(Screen):
pass

class RootWidget(ScreenManager):
pass

class Test(App):
def __init__(self, **kwargs):
super(Test, self).__init__(**kwargs)
self.previous_screen = ""

def build(self):
return RootWidget()

if __name__ == '__main__':
Test().run()

I used <Screen> and the on_leave property to make sure that the self.previous_screen updated after every screen change.

<Screen>:
on_leave: app.previous_screen = self.name

<Home>:
name: "home_screen"
GridLayout:
cols: 1
padding: 10
Button:
text: "To User Screen"
on_release: root.manager.current = "user_screen"

<User>:
name: "user_screen"
GridLayout:
cols: 1
padding: 10
Button:
text: "Back"
on_release: root.manager.current = app.previous_screen

<RootWidget>:
Home
User

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store