编写 MDDropdownMenu 项
Posted
技术标签:
【中文标题】编写 MDDropdownMenu 项【英文标题】:Write the MDDropdownMenu item 【发布时间】:2021-06-17 23:07:11 【问题描述】:我尝试在 MDDropdownMenu 中写入所选项目。 但是,即使有这段代码,我也找不到 menu.bind (.....) 函数没有任何结果
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部分
最好的问候
【问题讨论】:
【参考方案1】:使用MDDropdownMenu
的callback
属性:
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
中定义下拉菜单,如下所示:
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()
【讨论】:
以上是关于编写 MDDropdownMenu 项的主要内容,如果未能解决你的问题,请参考以下文章
如何将 MDDropdownMenu 放在 KivyMD 中的 MDlist 项目上?
无法让 MDDropdownMenu 和 MDDropDownItem 工作