我是一名德国学生,正在努力学习Kivy。我已经购买了O' Reilly的书"在Kivy中创建应用程序"进入这个主题。 作者说我应该用一个名为" AddLocationForm"的子Widget创建一个Root Widget。 KV代码:
#: import ListItemButton kivy.uix.listview.ListItemButton
#: import ListAdapter kivy.adapters.listadapter.ListAdapter
WeatherRoot:
<WeatherRoot>:
AddLocationForm:
orientation: "vertical"
search_input: search_box
search_results: search_result_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_result_list
adapter:
ListAdapter(data=[], cls=ListItemButton)
Python代码:
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.properties import ObjectProperty
from kivy.network.urlrequest import UrlRequest
class WeatherRoot(BoxLayout):
pass
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):
cities = ["{}({})".format(d['name'], d['sys']['country'])
for d in data['list']]
if not cities:
self.search_results.item_strings = ["Nothing found"]
else:
self.search_results.item_strings = cities
class WeatherApp(App):
pass
if __name__ == '__main__':
WeatherApp().run()
如果我现在按下按钮&#34;搜索&#34;当然会出现以下Traceback:
文件&#34;。\ weatherapp.kv&#34;,第18行,in on_press:root.search_location() AttributeError:&#39; WeatherRoot&#39;对象没有属性&#39; search_location&#39;
他必须搜索&#34; search_location&#34;在AddLocationForm中而不是在根类中的函数。 我尝试了以下步骤:
他们都没有奏效。根据作者的说法,它必须调用&#34; root.search_location()&#34;。
有没有人有想法?
答案 0 :(得分:1)
这本书错了。您可以通过以下方式修复它:
id: location_form
下添加AddLocationForm
location_form.search_location()
。此外:
root
引用WeatherRoot
。AddLocationForm
属性,因此app.AddLocationForm
无法正常工作。AddLocationForm
。这只是一个类,而不是实例。我们无法知道您想要引用哪个实例。我想作者首先在下面编写小部件,并将内容移动到,这会破坏一些事情:)