Creating DropDown in kivy with only kv file

时间:2015-06-15 14:34:51

标签: android python kivy

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.

1 个答案:

答案 0 :(得分:2)

是的,可以使用kivy语言。

您可以通过这些链接了解DropDownListSpinner。如果您想了解更多有关其工作的信息,您可能需要查看此link for kivy-showcase

我认为代码是自我解释的。(on_select方法)

这是main.py文件

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()

这是main.kv文件

<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')