我很难用Kivy的半纯蟒蛇和半kv语言设置系统。我现在所做的只是一个'hello world'
类型on_press
事件,我无法让它发挥作用。
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
#:import sla kivy.adapters.listadapter
<ListViewModal>:
ListView:
size_hint: .8, .8
adapter:
sla.ListAdapter(
data=["{0}".format(i) for i in root.categories],
on_press=root.callback(self),
cls=ListItemButton.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
SECTION_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',....
最终,我想为on_press
中每个标题为每个动态创建的按钮绑定SECTION_DICT
事件,然后将值保存在JsonStore
中。
简单来说,我需要做的就是让用户按一个按钮来选择一个craigslist类别,它将返回3个字母的缩写,以便稍后在程序中使用。
答案 0 :(得分:1)
ListAdapter
没有on_press
个事件。您需要绑定到每个按钮的on_press
事件,这可以使用args converter完成:
#:import ListItemButton kivy.uix.listview.ListItemButton
#:import ListAdapter kivy.adapters.listadapter.ListAdapter
<ListViewModal>:
ListView:
size_hint: .8, .8
adapter:
ListAdapter(
data=["{0}".format(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)
另外,注意将函数本身作为回调而不是函数的返回值传递。换句话说,请使用root.callback
代替root.callback(self)
。