Reputation: 4966
My App is a ScreenManager. Depending on the circumstances, I want the active screen to either be "Screen 1" or "Screen 2" when the app opens. How would I do this the most elegant way? I thought that this is as trivial as changing the current
property in the initialization of the app. Sadly, this does not work. Here's what should work imo:
main.py:
MyApp(App):
def build(self):
return Builder.load_file("MyApp.kv")
def __init__(self, **kwargs):
super(MyApp, self).__init__(**kwargs)
if foo: # Here's the problem:
self.root.current = "Screen 1"
else:
self.root.current = "Screen 2"
MyApp.kv:
ScreenManager:
Screen1:
name: "Screen 1"
Screen2:
name: "Screen 2"
<Screen1@Screen>
etc...
But it doesn't. Throws the following error:
self.root.current = "Screen 1"
AttributeError: 'NoneType' object has no attribute 'current'
My guess is that I set the current
attribute to early, before root
is set. An idea of mine is to 1) create a property-var for MyApp, 2) set current
to be that property, 3) change that property in the init method. That's a lot of effort and code-cluttering just to change a screen on initialization.
How would I do it? Thanks a lot in advance!
Upvotes: 0
Views: 680
Reputation: 575
Only this is working.
I said such statement as of I tryed many codes(but not works)
class NextScreen(ScreenManager):
def __init__(self,**kwargs):
super(NextScreen,self).__init__(**kwargs)
#code goes here and add:
Window.bind(on_keyboard=self.Android_back_click)
def Android_back_click(self,window,key,*largs):
# print(key)
if key == 27:
if self.current_screen.name == "Screen1" or self.current_screen.name == "Screen_main":
return False
elif self.current_screen.name == "Screen2":
try:
self.current = "Screen1"
except:
self.current = "Screen_main"
return True
Use 'esc' button to get key(27) which means back in android
Upvotes: 0
Reputation: 104
That's simply because you don't have self.root
object specified. Why would you need to change Screens during __init__
? You should use build
function for that.
My example:
import random
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.screenmanager import ScreenManager
Builder.load_string('''
<Root>:
Screen:
name: "Screen 1"
Label:
text: "Screen 1!"
Screen:
name:"Screen 2"
Label:
text: "Screen 2!"
''')
class Root(ScreenManager):
pass
class MyApp(App):
def build(self):
self.root = Root()
foo = random.randint(0,1)
if foo:
self.root.current = "Screen 1"
else:
self.root.current = "Screen 2"
return self.root
MyApp().run()
self.root.cureent_screen
property will be changed before self.root
object will be visible
Upvotes: 1