编写 MDDropdownMenu 项

2022-01-15 00:00:00 python kivy drop-down-menu screen

问题描述

我尝试在 MDDropdownMenu 中写入所选项目.但是,即使有这段代码,我也找不到menu.bind (.....) 函数没有任何结果

I try to write the selected item in MDDropdownMenu. But, even with this code, I don't find it I don't have any result with menu.bind (.....) function

from kivymd.app import MDApp
from kivymd.uix.menu import MDDropdownMenu
from kivy.lang import Builder
from kivy.clock import Clock
from kivymd.uix.screen import Screen


KV = """
<BuildApp>:

    MDRaisedButton:
        id: button
        text: "PRESS ME"
        pos_hint: {"center_x": .5, "center_y": .5}
        on_release: root.menu.open()

BuildApp:
"""

class BuildApp(Screen):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        Clock.schedule_once(self._late_init)

    def _late_init(self, interval):
        menu_items = [{"text": f"Item {i}"} for i in range(5)]
        self.menu = MDDropdownMenu(
            caller=self.ids.button,
            items=menu_items,
            width_mult=4,
        )
        self.menu.bind(on_release=self.menu_callback)



    def menu_callback(self, instance_menu, instance_menu_item):
        print(instance_menu, instance_menu_item)


class MainApp(MDApp):
    def build(self):
        self.root = Builder.load_string(KV)


MainApp().run()

另外,如何在.Kv文件中编写MDDropdownMenu部分

In addition, how can I write the MDDropdownMenu part in .Kv file

最好的问候


解决方案

使用MDDropdownMenucallback属性:

def _late_init(self, interval):
    menu_items = [{"text": f"Item {i}"} for i in range(5)]
    self.menu = MDDropdownMenu(
        caller=self.ids.button,
        items=menu_items,
        callback=self.menu_callback,
        width_mult=4,
    )

def menu_callback(self,instance_menu_item):
    print(instance_menu_item.text)

你可以在kv中定义下拉菜单,像这样:

You can define the drop down menu in the kv, like this:

from kivymd.app import MDApp
from kivymd.uix.menu import MDDropdownMenu
from kivy.lang import Builder
from kivy.clock import Clock
from kivymd.uix.screen import Screen


KV = """
<MyMenu>:
    items: [{'text':'item 0'}, {'text':'item 1'}, {'text':'item 2'}, {'text':'item 3'}, {'text':'item 4'}]
    caller: app.root.ids.button
    callback: app.root.menu_callback
    width_mult: 4

<BuildApp>:
    MDRaisedButton:
        id: button
        text: "PRESS ME"
        pos_hint: {"center_x": .5, "center_y": .5}
        on_release: root.menu.open()

BuildApp:
"""

class MyMenu(MDDropdownMenu):
    pass


class BuildApp(Screen):

    def menu_callback(self, instance_menu_item):
        print(instance_menu_item.text)


class MainApp(MDApp):
    def build(self):
        root = Builder.load_string(KV)
        Clock.schedule_once(self.build_menu)
        return root

    def build_menu(self, dt):
        # cannot create menu until after app is built because of references to app.root in kv
        self.root.menu = MyMenu()


MainApp().run()

相关文章