Reputation: 605
I have an app with 2 screens (ScreenManager
).
I wrote a function in the second screen (SettingsScreen
) and I want this function to update a label in the first screen.
Below the two classes:
class MenuScreen(Screen):
count = NumericProperty(30)
class SettingsScreen(Screen):
def set_20(self):
self.count = 20
The classes are linked to a button and a label in the Kivy stylesheet with two different screens
<MenuScreen>:
FloatLayout:
orientation: 'horizontal'
Label:
id: l_label
text: str(root.count)
<SettingsScreen>:
BoxLayout:
orientation: 'vertical'
padding: 50
FloatLayout:
Button:
text: "20"
on_release: root.set_20()
To be clearer, the user has to click on the Button
in the SettingsScreen
to set the value of the NumericProperty
in the first screen to 20.
At the moment, if I click on the button nothing happens.
What you see above is an extract - The full code of the app is stored below if you want to see more.
https://github.com/marcogdepinto/LifeCounter
Thanks in advance for your help.
Upvotes: 1
Views: 628
Reputation: 1282
I think the problem is that when your button gets clicked and calls the set_20
method, that method is trying to set the property count
of the SettingsScreen
to 20.
In other words
def set_20(self):
self.count = 20
would try to set the the count property inside the SettingsScreen
(hence the word self
) and it cannot find it. There is another count
property inside MenuScreen
which it knows nothing about.
To fix this I think you should give an id to MenuScreen
<MenuScreen>:
id: menu
and in the on_release method of the Button do
on_release: menu.count = 20
Python file
class MenuScreen(Screen):
counter = NumericProperty(0)
class SettingsScreen(Screen):
pass
class MyWidget(ScreenManager):
pass
class MyRandomApp(App):
def build(self):
return MyWidget()
if __name__ == '__main__':
MyRandomApp().run()
<MyWidget>:
id:manager
MenuScreen:
id: menu
name: 'menuscreen'
BoxLayout:
orientation: 'vertical'
Label:
text: str(menu.counter)
Button:
text: 'Go to S2'
on_press: manager.current = 'settingsscreen'
SettingsScreen:
id: settings
name: 'settingsscreen'
BoxLayout:
orientation: 'vertical'
Button:
text: 'Click to edit label of Prev screen'
on_press: menu.counter = 20
Button:
text: 'Go to S1'
on_press: manager.current = 'menuscreen'
Upvotes: 2