Commit d1c9173c authored by Brady James Garvin's avatar Brady James Garvin
Browse files

Show how to makee data computed and stored in the main app class available to a screen.

parent f18f6b6d
......@@ -6,6 +6,9 @@
Button:
text: 'This button prints a number.'
on_press: root.print_number() # In a custom widget's Kv, `root` refers to the custom widget.
Button:
text: 'This button rolls a new number.'
on_press: app.reroll()
Button:
text: 'Change…'
on_press: app.open_second_screen() # But `app` still refers to the application object.
from random import randrange
from kivy.app import App
from kivy.properties import BooleanProperty, StringProperty
from kivy.properties import BooleanProperty, NumericProperty, StringProperty
# The following lines ensure that FirstScreen and SecondScreen are available for when the Kv code is loaded.
......@@ -16,6 +18,8 @@ class TwoScreenApp(App):
advancing = BooleanProperty(True)
current_screen_name = StringProperty() # We must wait to select a screen until the app starts.
roll = NumericProperty(1)
def open_first_screen(self):
self.advancing = True
self.current_screen_name = 'first'
......@@ -24,6 +28,12 @@ class TwoScreenApp(App):
self.advancing = False
self.current_screen_name = 'second'
def reroll(self):
new_roll = randrange(1, 6)
if new_roll >= self.roll:
new_roll +=1
self.roll = new_roll
def on_start(self):
self.open_first_screen() # Once the app starts, we can select the starting screen.
......
......@@ -5,6 +5,9 @@
text: 'This is the second screen.'
Label:
text: root.message # In a custom widget's Kv, `root` refers to the custom widget.
Button:
text: 'This button prints the roll from the first screen.'
on_press: root.print_roll()
Button:
text: 'Change…'
on_press: app.open_first_screen() # But `app` still refers to the application object.
from kivy.lang import Builder
from kivy.uix.screenmanager import Screen
from kivy.properties import StringProperty
from kivy.properties import NumericProperty, StringProperty
Builder.load_file('second_screen.kv') # Because this is not the main app, we must load the Kv explicitly.
......@@ -8,3 +8,7 @@ Builder.load_file('second_screen.kv') # Because this is not the main app, we mu
class SecondScreen(Screen):
message = StringProperty('Hello, World!') # This property is changed by twoscreen.kv.
roll = NumericProperty()
def print_roll(self):
print(f'The latest roll was a {self.roll}.')
......@@ -11,3 +11,4 @@ ScreenManager:
SecondScreen:
name: 'second'
message: 'This is a message!' # The app sends information to the custom widgets by setting their properties.
roll: app.roll
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment