Creating DropDown in kivy with only kv file

16.9k Views Asked by At

I wanted to get a simple combo box like widget using the DropDown class. I can do it using python code, but is it possible using just kv language?

I tried the following. Here's my python code:

class CustomDropDown(DropDown):
   pass

class MainForm(BoxLayout):
    pass

class MainApp(App):
    def build(self):
        self.dropdown = CustomDropDown()
        self.mainForm = MainForm()
        return self.mainForm
    def do_something(self):
        self.dropdown.open(self.mainForm)

MainApp().run()

And here's the kv file :

<MainForm>:
    Button:
        text: 'Press'
        size_hint: [None,None]
        height: '40dp'
        on_release: app.do_something()
<CustomDropDown>:
    Button:
        text: 'First Item'
    Label:
        text: 'Disabled item'
    Button:
        text: 'Second Item'

But this is not working. Can you please suggest something? Any help is appreciated.

2

There are 2 best solutions below

1
On

Yes, it's possible using kivy language.

You can read about DropDownList or Spinner through these links. And also if you want to know more on their working, you might want to check this link for kivy-showcase

I think the code is self explanatory.(on_select method)

This is the main.py file

from kivy.app import App
from kivy.uix.dropdown import DropDown
from kivy.uix.boxlayout import BoxLayout

class CustomDropDown(BoxLayout):
    pass

class MainApp(App):
    def build(self):
        return CustomDropDown()
if __name__=='__main__':
    MainApp().run()

This is the main.kv file

<CustomDropDown>:

    Button:
        id: btn
        text: 'Press'
        on_release: dropdown.open(self)
        size_hint_y: None
        height: '48dp'

    DropDown:

        id: dropdown
        on_parent: self.dismiss()
        on_select: btn.text = '{}'.format(args[1])

        Button:
            text: 'First Item'
            size_hint_y: None
            height: '48dp'
            on_release: dropdown.select('First Item')

        Label:
            text: 'Second Item'
            size_hint_y: None
            height: '48dp'

        Button:
            text: 'Third Item'
            size_hint_y: None
            height: '48dp'
            on_release: dropdown.select('Third Item')
0
On

You could try something like this in your kv file:

Button:
    text: "Press"
    size_hint: None, None
    size: 250, 50
    pos_hint: {"center": (0.5, 0.5)}
    on_release: Factory.CustomDropDown().open(self)

<CustomDropDown@DropDown>:
    Button:
        text: 'First Item'
        size_hint_y: None
        height: 44
        on_release: root.select('item1')
    Label:
        text: 'Disabled item'
        size_hint_y: None
        height: 44
    Button:
        text: 'Second Item'
        size_hint_y: None
        height: 44
        on_release: root.select('item2')

And completely remove CustomDropDown class from your py file.