When you have a screenmanager with one screen, in kvlang:
<ScreenManagement>:
ScreenOne:
<ScreenOne>:
name: 'First'
id: screen1
<ScreenTwo>:
name: 'Second'
id: screen2
And as can be seen, you also have a second screen defined, but it is not added to the screenmanager.
How do you add it with python? (I want to do it based on some condition from a config file)
I know I can add a widget to the screenmanager with add_widget()
but I don't know how to reference the ScreenTwo from python.
I tried with ids but I get an keyError with this code:
class ScreenManagement(ScreenManager):
def __init__(self,**kwargs):
super().__init__(**kwargs)
def setup(*args):
if True: #under some condition, I want to add ScreenTwo
#this does not work: KeyError
screen_widget = App.get_running_app().root.ids['screen2']
self.add_widget(screen_widget)
Clock.schedule_once(setup)
First, in your kv
file, make sure ScreenTwo
is a subclass of Screen
: <ScreenTwo@Screen>:
. Second, the angle brackets indicate a rule rather than an actual instantiation. It just means that if an object matching the rule is instantiated, it will get these properties. To instantiate an instance of ScreenTwo
in your Python code, use Factory
:
screen_widget = Factory.ScreenTwo()
You are doing a few things wrong. First the things in <
and >
are called rules. These rules govern how the class is made whenever you invoke ScreenOne()
in Python or in kv. Second, you are not able to add an id to a rule then access that id from a root widget. The correct way to do it is in my kv file. You move the id into the <ScreenManagement>
rule. Lastly, you can always see what is going on with your kv file by doing a print self.children
.
kvlang = '''
<ScreenManagement>:
ScreenOne:
id: screen1
<ScreenOne>:
name: 'First'
<ScreenTwo>:
name: 'Second'
'''
class ScreenManagement(ScreenManager):
def __init__(self,**kwargs):
super(ScreenManagement,self).__init__(**kwargs)
Clock.schedule_once(self.setup)
def setup(self,*args):
if True: #under some condition, I want to add ScreenTwo
print self.children, self.current
self.add_widget(ScreenTwo())
self.current = 'Second'
print self.children, self.current
print self.ids
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.