如何获得Kivy应用程序以打开下拉菜单

时间:2019-01-08 20:09:42

标签: python kivy

我正在尝试使用kivy应用程序来打开下拉菜单。我正在关注示例here

当我运行该应用程序时,我可以单击该按钮,但不会显示任何下拉列表。

我缺少一些简单的东西,但是我看不到它。有人可以帮忙吗。

from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.screenmanager import Screen
from kivy.uix.dropdown import DropDown
from kivy.uix.button import Button
from kivy.lang import Builder

root = Builder.load_string('''
<MainFrame>:
    BoxLayout:
        orientation: 'vertical'
        Label:
            text: 'Hello'
        Button:
            text: 'open dropdown'
            on_press: root.on_menu_button_click()
''')

class MainFrame(Screen):
    def __init__(self, **kwargs):
        super(MainFrame, self).__init__(**kwargs)
        self.dropdown = self._create_dropdown()

    def _create_dropdown(self):
        dropdown = DropDown()
        for index in range(5):
            btn = Button(text='Value %d' % index, size_hint_y=None, height=44)
            btn.bind(on_release=lambda btn: dropdown.select(btn.text))
            dropdown.add_widget(btn)
        return dropdown

    def on_menu_button_click(self):
        self.dropdown.open

class BasicApp(App):
    def build(self):
        return MainFrame()

if __name__ == '__main__':
    BasicApp().run()

1 个答案:

答案 0 :(得分:1)

您必须使用open()方法并通过按钮,还必须使用on_release而不是on_press

from kivy.app import App
from kivy.uix.screenmanager import Screen
from kivy.uix.dropdown import DropDown
from kivy.uix.button import Button
from kivy.lang import Builder

root = Builder.load_string('''
<MainFrame>:
    BoxLayout:
        orientation: 'vertical'
        Label:
            text: 'Hello'
        Button:
            id: btn  # <---
            text: 'open dropdown'
            on_release: root.on_menu_button_click(btn) # <---
''')

class MainFrame(Screen):
    def __init__(self, **kwargs):
        super(MainFrame, self).__init__(**kwargs)
        self.dropdown = self._create_dropdown()

    def _create_dropdown(self):
        dropdown = DropDown()
        for index in range(5):
            btn = Button(text='Value %d' % index, size_hint_y=None, height=44)
            btn.bind(on_release=lambda btn: dropdown.select(btn.text))
            dropdown.add_widget(btn)
        return dropdown

    def on_menu_button_click(self, widget): # <---
        self.dropdown.open(widget) # <---

class BasicApp(App):
    def build(self):
        return MainFrame()

if __name__ == '__main__':
    BasicApp().run()

上面的示例清楚地表明了上述内容,因为它表明:

...
# show the dropdown menu when the main button is released
# note: all the bind() calls pass the instance of the caller (here, the
# mainbutton instance) as the first argument of the callback (here,
# dropdown.open.).
mainbutton.bind(on_release=dropdown.open)
...