Reputation: 67
So, here is what I'm trying to do: when entering on the first screen of my app, I want it to check if some files exist in given directory. If they exist, I want it to immediately change to another screen.
I've tried the following:
main.py
from kivy.app import App
from kivy.uix.screenmanager import ScreenManager, Screen
from os import listdir
class Manager(ScreenManager):
pass
class CreateFileScreen(Screen):
def on_enter(self):
try:
files = listdir("data/files")
if "file.dat" in files:
self.parent.current = "login"
else:
pass
except FileNotFoundError:
pass
class LoginScreen(Screen):
pass
class ExampleApp(App):
def build(self):
return Manager()
if __name__ == "__main__":
ExampleApp().run()
example.kv
#:kivy 1.10.0
<CreateFileScreen>:
BoxLayout:
Label:
text: "This is Create File Screen"
font_size: "30sp"
<LoginScreen>:
BoxLayout:
Label:
text: "This is Login Screen"
font_size: "30sp"
<Manager>:
CreateFileScreen:
name: "createfile"
LoginScreen:
name: "login"
When file.dat
does exist in data/files
I get the following error:
kivy.uix.screenmanager.ScreenManagerException: No Screen with name "login".
Any idea on how to fix this?
Upvotes: 5
Views: 8204
Reputation: 5405
The problem is that on_enter
is executed before the screen gets its name.
You can make a change_screen
method, then call it with Clock.schedule_once
. That way it will be called the next frame.
from kivy.clock import Clock
class CreateFileScreen(Screen):
def on_enter(self):
Clock.schedule_once(self.change_screen)
def change_screen(self, dt):
try:
files = listdir("data/files")
if "file.dat" in files:
self.manager.current = "login"
else:
pass
except Exception as e:
print(e)
Upvotes: 8