我是Kivy的新手,非常喜欢Kivy文件中代码和UI规范之间的分离。我在理解如何在Kivy文件中定义ListAdapter时遇到了障碍。例如,这是一个在Python代码中完全定义的ListAdapter:
class TestPop(Popup):
a = ['a', 'b', 'c', 'd', 'e', 'f','g']
def __init__(self, **kwargs):
super(TestPop, self).__init__(**kwargs)
aAdapter = ListAdapter(data=self.a, cls=ListItemButton,
args_converter = lambda row_index, x: {'text': x,'size_hint_y': None,
'height': 50})
aAdapter.bind(on_selection_change=self.click)
myBox = BoxLayout(orientation = 'vertical')
myBox.add_widget(ListView(size_hint = (1,0.8), adapter = aAdapter))
myBox.add_widget(Label(text = 'my pop', size_hint = (1,0.2)))
self.add_widget(myBox)
self.open
def click(self, *args):
print('click:{}'.format(args[0].selection[0].text))
现在,我可以通过将Python代码更改为:
将部分UI定义放入kivy文件中class TestPop2(Popup):
a = ['a', 'b', 'c', 'd', 'e', 'f','g']
def __init__(self, **kwargs):
self.aAdapter = ListAdapter(data=self.a, cls=ListItemButton,
args_converter = lambda row_index, x: {'text': x,'size_hint_y': None,
'height': 50})
self.aAdapter.bind(on_selection_change=self.click)
super(TestPop2, self).__init__(**kwargs)
self.open
def click(self, *args):
print('click:{0}'.format(args[0].selection[0].text))
并创建一个Kivy文件:
<TestPop2>:
title: 'type2 popup'
BoxLayout:
orientation: 'vertical'
ListView:
size_hint: (1,0.8)
adapter: root.aAdapter
Label:
text: 'Test2 pop'
size_hint: (1,0.2)
这会奏效。但是,我将ListAdapter移动到kivy文件时遇到问题。我试过这段代码:
class TestPop3(Popup):
'''uses kv file but can't get on_selection_change to work
'''
a = ListProperty(['a', 'b', 'c', 'd', 'e', 'f','g'])
def __init__(self, **kwargs):
super(TestPop3, self).__init__(**kwargs)
self.open
def click(self, *args):
print('click:{0}'.format(args[0].selection[0].text))
使用此kv文件:
<TestPop3>:
title: 'type3 popup'
BoxLayout:
orientation: 'vertical'
ListView:
size_hint: (1,0.8)
adapter: ListAdapter(data=root.a,cls=ListItemButton,args_converter= lambda row_i, x:{'text':x,'size_hint_y':None,'height':50},on_selection_change= root.click)
Label:
text: 'Test3 pop'
size_hint: (1,0.2)
但是on_selection_change不起作用。我假设在何时或如何将函数绑定到事件时有一些关键的东西,并且试图通过ObjectProperty将引用传递回Python代码,但我无法弄明白。
Kivy ListAdapter文档位于http://kivy.org/docs/api-kivy.adapters.listadapter.html,但我无法在那里找到解决方案。一些优秀的代码示例位于http://kivy.org/docs/api-kivy.uix.listview.html,但我没有看到任何帮助我解决此问题的代码。
我也是Python的新手,所以如果有关于在描述这个问题时使我的代码更具Pythonic或更准确的术语的评论,我全心全意。