vanbear vanbear - 1 year ago 99
Python Question

Init screen in kv on button release using ScreenManager

I'm a beginner Kivy developer and I need some advice from you guys.
I'm using ScreenManager to jump between screens and as far as I noticed, all the screens are initialized just after the application starts, and I need them to be initialized with certain attributes from previous screens, like, selecting the category or stuff. Is there any way to do that?

I have two buttons in CategorySelectScreen both representing certain category, I want them to send a string attribute to DictScreen, where it will be used as an argument in CategorySelect method, which filters the items list, but the thing is, the application need that argument on start and without it the interpreter would just throw errors.

Also, I think I'm using kivy in a very bad way, could you please look into my code and give me some pro tips? Thanks in advance, cheers :)

kv file: http://pastebin.com/UdvGS7Wv

py files: http://pastebin.com/gJn9Mrip

Answer Source

When declaring your screens decide what object would be it's input. Then make this object a property. After that, setup on_... callback where you build your screen with widgets with values based on this input object. For example:

class DictScreen(Screen):
   category_selected = ObjectProperty(None)

   def on_category_selected(self, instance, value):
      category_selected = value
      self.clear_widgets()
      self.add_widget(Button(text=category_selected.name))

And in previous screen, before you switch to DictScreen get its instance from app.root.ids, then assign category_selected to it and then set new current screen with ScreenManager. This way your DictScreen will be immediately build with choosen category right before you switch to it.

"before you switch to DictScreen get its instance" how this can be done? It's well explained here: https://kivy.org/docs/api-kivy.uix.widget.html?highlight=widget#kivy.uix.widget.Widget.ids

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download