这是我理解的一个例子,你正在努力实现。它基于最简单的ListView 示例。请注意,我根据您提供的示例创建了一个扩展的 JSON 版本。此外,当您想使用 url 时,您必须替换 2 条注释行。加载json的方法是load
(用于io输入)而不是loads
(用于字符串输入)。
from kivy.uix.listview import ListView
from kivy.uix.gridlayout import GridLayout
import json
import urllib2
class MainView(GridLayout):
def __init__(self, **kwargs):
kwargs['cols'] = 2
super(MainView, self).__init__(**kwargs)
the_string_json = '{"meta": {"previous": null, "total_count": 8, "offset": 0, "limit": 20, "next": null}, "objects": [{"id": 1, "page_count": 155, "description": "Cool book", "title": "Kivy book 1"}, {"id": 1, "page_count": 155, "description": "Cool book", "title": "Kivy book 2"}, {"id": 1, "page_count": 155, "description": "Cool book", "title": "Kivy book 3"}]}'
the_dict = json.loads(the_string_json)
# Substitute the previous two lines for this ones:
# the_io_json = urllib2.urlopen('mysite.com/api/books/?format=json')
# the_dict = json.load(the_io_json)
list_view = ListView(
item_strings=[book['title'] for book in the_dict['objects']])
self.add_widget(list_view)
if __name__ == '__main__':
from kivy.base import runTouchApp
runTouchApp(MainView(width=800))