首页 > 解决方案 > 如何让 kivy 应用打开下拉菜单

问题描述

我正在尝试让一个 kivy 应用程序打开一个下拉列表。我在这里按照示例进行操作。

当我运行应用程序时,我可以单击按钮,但没有出现下拉菜单。

我错过了一些简单的东西,但我就是看不到它。有人可以帮忙吗。

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

标签: pythonkivy

解决方案


您必须使用该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)
...

推荐阅读