2

I've copied this code from a book about Kivy and python

main.py

from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.properties import ObjectProperty
from kivy.network.urlrequest import UrlRequest

import json

class AddLocationForm(BoxLayout):
    search_input = ObjectProperty()
    search_results = ObjectProperty()

    def search_location(self) :
        search_template = "http://api.openweathermap.org/data/2.5/find?q={}&type=like"
        search_url = search_template.format(self.search_input.text)
        request = UrlRequest(search_url, self.found_location)

    def found_location(self, request, data) :
        data = json.loads(data.decode())
        cities = [ "{} ({})".format(d['name'], d['sys']['country']) for d in data['list'] ]
        self.search_results.item_strings = cities

class WeatherApp(App):
    pass


if __name__ == "__main__" :
    WeatherApp().run()

weather.kv

AddLocationForm:

<AddLocationForm>:
    orientation: "vertical"
    search_input: search_box
    search_results: search_results_list
    BoxLayout:
        height: "40dp"
        size_hint_y: None
        TextInput: 
            id: search_box
            size_hint_x: 50
        Button:
            text: "Search"
            size_hint_x: 25
            on_press: root.search_location()
        Button:
            text: "Current location"
            size_hint_x: 25
    ListView:
        id : search_results_list
        item_strings: []

Why do I get the following error?

Traceback (most recent call last):
 File "main.py", line 27, in <module>
   WeatherApp().run()
 File "C:\Kivy\kivy\kivy\app.py", line 765, in run
   self.load_kv(filename=self.kv_file)
 File "C:\Kivy\kivy\kivy\app.py", line 585, in load_kv
   root = Builder.load_file(rfilename)
 File "C:\Kivy\kivy\kivy\lang.py", line 1444, in load_file
   return self.load_string(data, **kwargs)
 File "C:\Kivy\kivy\kivy\lang.py", line 1491, in load_string
   parser = Parser(content=string, filename=fn)
 File "C:\Kivy\kivy\kivy\lang.py", line 1049, in __init__
   self.parse(content)
 File "C:\Kivy\kivy\kivy\lang.py", line 1122, in parse
   objects, remaining_lines = self.parse_level(0, lines)
 File "C:\Kivy\kivy\kivy\lang.py", line 1218, in parse_level
   level + 1, lines[i:], spaces)
 File "C:\Kivy\kivy\kivy\lang.py", line 1228, in parse_level
   'Invalid property name')
kivy.lang.ParserException: Parser: File ".\weather.kv", line 21:
...
    19:                       size_hint_x: 25
    20:       ListView:
>>   21:               id : search_results_list
    22:               item_strings: []
...
Invalid property name
4

1 回答 1

7
id : search_results_list

这是因为你在 id 后面有一个空格,应该是

id: search_results_list

如果这在书中,我想这是一个错字。

于 2014-04-26T21:01:57.800 回答