Reputation: 385
I developed an UI with Kivy / KivyMD with Python. The UI is very simple: when a button is pressed a DropDownItem is added to the layout. I need to add a method that is called every time the selection of the DropDownItem changes. Here is the code:
from kivy.lang import Builder
from kivymd.app import MDApp
from kivymd.uix.screen import MDScreen
from kivymd.toast import toast
from kivymd.uix.menu import MDDropdownMenu
from kivymd.uix.dropdownitem.dropdownitem import MDDropDownItem
from kivy.metrics import dp
Builder.load_string(
"""
<View>:
MDGridLayout:
rows: 3
id: layout
padding: 100, 50, 100, 50
spacing: 0, 50
MDRaisedButton:
text: 'CREATE DDI'
on_release: root.Button_CreateDDI__On_Click()
MDRaisedButton:
id: button_check
disabled: True
text: 'CHECK SELECTION'
on_release: root.Button_CheckSelection_On_Click()
""")
class View(MDScreen):
def __init__(self, **kwargs):
super(View, self).__init__(**kwargs)
def Button_CreateDDI__On_Click(self):
self.myDdi = MDDropDownItem()
self.myDdi.text = 'SELECT POSITION'
myMenu, scratch = self.Create_DropDown_Widget(self.myDdi, ['POS 1', 'POS 2', 'POS 3'], width=4)
self.myDdi.on_release = myMenu.open
self.myDdi.bind(on_select = self.DDI_Selection_Changed)
self.ids.button_check.disabled = False
self.ids.layout.add_widget(self.myDdi)
def Button_CheckSelection_On_Click(self):
toast('CURRENT VALUE: ' + self.myDdi.current_item)
def DDI_Selection_Changed(self):
toast('SELECTION CHANGED: ' + self.myDdi.current_item)
def Create_DropDown_Widget(self, drop_down_item, item_list, width):
items_collection = [
{
"viewclass": "OneLineListItem",
"text": item_list[i],
"height": dp(56),
"on_release": lambda x = item_list[i]: self.Set_DropDown_Item(drop_down_item, menu, x),
} for i in range(len(item_list))
]
menu = MDDropdownMenu(caller=drop_down_item, items=items_collection, width_mult=width)
menu.bind()
return menu, items_collection
def Set_DropDown_Item(self, drop_down_item, menu, text_item):
drop_down_item.set_item(text_item)
menu.dismiss()
class MainApp(MDApp):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.View = View()
def build(self):
self.title = ' DROP DOWN ITEM ADDED DYNAMICALLY'
return self.View
if __name__ == '__main__':
MainApp().run()
When the DropDownItem is added in the kv part, you can use the select event. Here the widget is added once the layout is already displayed. So I tried to bind the on_select event, but nothing occured neither an error or an exception. How to call a method everytime the selection of a DropDownItem changes?
Upvotes: 1
Views: 213
Reputation: 31
You already have a function that is invoked whenever an item in the dropdown menu is selected. I would just move the toast there.
def Set_DropDown_Item(self, drop_down_item, menu, text_item):
drop_down_item.set_item(text_item)
menu.dismiss()
toast('CURRENT VALUE: ' + text_item )
Upvotes: 0