我有一个标题的词典,其值代表3个字母的缩写。
我有一个带标题的按钮列表,我需要on_click来返回缩写。
我现在所拥有的内容会返回标题(按钮文本),但我无法弄清楚如何传递整个字典条目,或只是传递值。
from kivy.uix.modalview import ModalView
from kivy.uix.listview import ListView
from kivy.uix.gridlayout import GridLayout
from kivy.lang import Builder
from kivy.app import App
import citylists
import cat_dict
from kivy.uix.screenmanager import ScreenManager, Screen, FadeTransition
from kivy.storage.jsonstore import JsonStore
store = JsonStore('data.json')
Builder.load_string("""
#:import ListItemButton kivy.uix.listview.ListItemButton
#:import ListAdapter kivy.adapters.listadapter.ListAdapter
<ListViewModal>:
ListView:
size_hint: .8, .8
adapter:
ListAdapter(
data=[i for i in root.categories],
args_converter=lambda row_index, rec: \
{'text': rec, 'on_press': root.callback, 'size_hint_y': None, 'height': 25},
cls=ListItemButton)
""")
class ListViewModal(ModalView):
categories = sorted(cat_dict.SECTION_DICT)
def __init__(self, **kwargs):
super(ListViewModal, self).__init__(**kwargs)
def callback(self, instance):
print "HI" + str(instance)
class MainView(GridLayout):
def __init__(self, **kwargs):
kwargs['cols'] = 1
super(MainView, self).__init__(**kwargs)
listview_modal = ListViewModal()
self.add_widget(listview_modal)
class MainScreen(Screen):
pass
mainscreen=MainScreen()
mainlayout = MainView()
mainscreen.add_widget(mainlayout)
sm = ScreenManager()
sm.add_widget(mainscreen)
class CARApp(App):
def build(self):
return sm
if __name__ == '__main__':
CARApp().run()
cat_dict.py
EECTION_DICT = {
"accounting+finance": "acc",
"admin / office": "ofc",
"arch / engineering": "egr",
'art / media / design': 'med',
'biotech / science': 'sci',
'business / mgmt': 'bus',
'customer management': 'csr',
'education': 'edu',....
答案 0 :(得分:2)
看起来你实际上不必将任何内容传递给回调。看起来如下所示:
class ListViewModal(ModalView):
section_dict = cat_dict.SECTION_DICT
categories = sorted(section_dict)
def __init__(self, **kwargs):
super(ListViewModal, self).__init__(**kwargs)
def callback(self, instance):
print "HI" + str(instance)
# Print abbreviation from dictionary lookup
print ListViewModal.section_dict[instance.text]
哪个输出:
HI<ListItemButton text=accounting+finance> acc
但是将一些额外的参数传递给你的回调的方法是改变
'on_press': root.callback
# to
'on_press': lambda inst: root.callback(inst, 'some arg')
然后改变
def callback(self, instance):
# to
def callback(self, instance, arg):
The docs除了使用lambda函数外,还使用itertools.partial
作为选项列出。
答案 1 :(得分:1)
EECTION_DICT = {
"accounting+finance": "acc",
"admin / office": "ofc",
"arch / engineering": "egr",
'art / media / design': 'med',
'biotech / science': 'sci',
'business / mgmt': 'bus'}
def foo(args):
for item in args.items():
print(item)
foo(EECTION_DICT)
或
def foo(**args):
for key,item in args.items():
print(key, item)
foo(**EECTION_DICT)