Many classes of screens with repeated functions | How do I create a function for all classes?

45 views
Skip to first unread message

Felipe Viera

unread,
Apr 5, 2020, 8:34:29 PM4/5/20
to Kivy users support
Hello! I made an app with several classes of screens with repeated codes:

class screen1(Screen):
def on_pre_enter(self):
Window.bind(on_keyboard=self.voltar)
def voltar(self, window, key, *args):
if key == 27:
MDApp.get_running_app().root.transition.direction = 'right'
MDApp.get_running_app().root.current = 'menu'
return True
def on_pre_leave(self):
Window.unbind(on_keyboard=self.voltar)

class screen2(Screen):
def on_pre_enter(self):
Window.bind(on_keyboard=self.voltar)
def voltar(self, window, key, *args):
if key == 27:
MDApp.get_running_app().root.transition.direction = 'right'
MDApp.get_running_app().root.current = 'menu'
return True
def on_pre_leave(self):
Window.unbind(on_keyboard=self.voltar)

class screen3(Screen):
def on_pre_enter(self):
Window.bind(on_keyboard=self.voltar)
def voltar(self, window, key, *args):
if key == 27:
MDApp.get_running_app().root.transition.direction = 'right'
MDApp.get_running_app().root.current = 'menu'
return True
def on_pre_leave(self):
Window.unbind(on_keyboard=self.voltar)
# 18 screens...

And I want to copy the functions of one screen and paste in all others to decrease the code:

class ScreenClass():
def on_pre_enter(self):
Window.bind(on_keyboard=self.voltar)
def voltar(self, window, key, *args):
if key == 27:
MDApp.get_running_app().root.transition.direction = 'right'
MDApp.get_running_app().root.current = 'menu'
return True
def on_pre_leave(self):
Window.unbind(on_keyboard=self.voltar)

class screen1(Screen):
ScreenClass.on_pre_enter()
ScreenClass.voltar()
ScreenClass.on_pre_leave()

class screen2(Screen):
ScreenClass.on_pre_enter()
ScreenClass.voltar()
ScreenClass.on_pre_leave()

class screen3(Screen):
ScreenClass.on_pre_enter()
ScreenClass.voltar()
ScreenClass.on_pre_leave()

But I get an error, I also tried using @classmethod, but it returns an error. I tried many ways, when I don't get an error, the functions don't work :(

Robert Flatt

unread,
Apr 5, 2020, 10:11:20 PM4/5/20
to Kivy users support
That should be     ScreenClass(Screen) :
Then just use ScreenClass()  everywhere you use screen1() , screen2() , screen3()
Forget screen1() , screen2() , screen3()
Because you can have more than one instance of a Class.

Felipe Viera

unread,
Apr 6, 2020, 12:29:52 PM4/6/20
to Kivy users support
Thank you Robert! The functions did not work,
but I managed with:

class screen1(ScreenClass):
pass

class screen2(ScreenClass):
pass

class screen3(ScreenClass):
pass
Reply all
Reply to author
Forward
0 new messages