I have a simple program with a spinner widget to select a direction. I need to pass that direction as a variable that can be used in other classes. In the code below, I just want to print the direction in my main app class
#main.py
from kivy.uix.widget import Widget
from kivy.app import App
class MenuKV(Widget):
spun = False
value = str
def on_spinner_select(self, value):
# print (val)
self.value = value
self.spun = True
class MenuScreen(App):
def build(self):
if MenuKV.spun == True:
print ("your Going "+ MenuKV.value)
MenuScreen().run()
#kv file #menuscreen.kv
MenuKV:
<MenuKV>:
BoxLayout:
orientation: 'horizontal'
pos_hint: {"x":0, "top":1}
size_hint: 1, None
height: "44dp"
width: "200dp"
spacing: "10dp"
padding: "10dp"
pos: 0, root.height - 60
Spinner:
id: direction
text: 'North'
values: 'North', 'South', 'East', 'West'
on_text:
value = direction.text
root.on_spinner_select(value)
Button:
text: "future dev"
Firstly, your code as it is doesn't seem to work as the spinner is not even displayed when you start the app. I assume this was not an intention as to actually print something, your code expects that a value has been selected on the spinner.
Secondly, why are you trying to print the selected value in the App class and not directly from the function that generated it?
If I modify the code in your
.pyfile to actually display the widgets, then to make the direction printed to terminal each time you select a value, all you need to do is this:If you really need to share variables across classes, one way to do it is to initiate variables outside the classes and let individual classes read/write them declaring them to be
globalinside your class functions.For example doing the below, you could access the
selected_valuefrom any other class and/or function: