尝试通过"在Kivy中创建应用程序" Dusty Phillips的书,但是有一个部分非常含糊,导致代码无法正常运行。我相信我知道这个问题,但不知道如何解决它。
这是我的.kv文件:
WeatherRoot:
<WeatherRoot>:
AddLocationForm:
orientation: 'vertical'
search_input: search_box
search_results: search_results_list
BoxLayout:
height: '48dp'
size_hint_y:None
TextInput:
multiline:False
write_tab:False
id: search_box
size_hint_x:50
on_text_validate: root.search_location()
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
adapter:
ListAdapter(data=[],cls=ListItemButton)
因为on_press和on_text_validate转到root,而我的root(在本例中是WeatherRoot)不包含search_location()函数,所以当我尝试搜索时会崩溃。
这是我的python代码:
from kivy.app import App from kivy.uix.boxlayout import BoxLayout from kivy.properties import ObjectProperty from kivy.network.urlrequest import UrlRequest
owm_key = 'xxxxxxxxxxxxx'
class WeatherRoot(BoxLayout):
pass
class AddLocationForm(BoxLayout):
search_input = ObjectProperty()
def search_location(self):
search_template = 'http://api.openweathermap.org/data/2.5/find?q={}&type=like&APPID='+ owm_key
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()) if not isinstance(data,dict) else data
cities = ['{} ({})'.format(d['name'],d['sys']['country']) for d in data['list']]
self.search_results.item_strings = cities
self.search_results.adapter.data.clear()
self.search_results.adapter.data.extend(cities)
self.search_results.__trigger__reset_populate()
class WeatherApp(App):
pass
if __name__ == '__main__': WeatherApp().run()
因为我的WeatherRoot类为空,使用
root.search_location()
什么都不做。有没有办法引用不是根,但是&#34;一个级别&#34;?另一方面,有没有其他人通过这本书,你是如何处理这一部分的?
谢谢! 戴夫
答案 0 :(得分:0)
这最终为我工作,只需要提升一级&#34; widget是一个id,并引用它:
WeatherRoot:
<WeatherRoot>:
AddLocationForm:
id: addlocationform
orientation: 'vertical'
search_input: search_box
search_results: search_results_list
BoxLayout:
height: '48dp'
size_hint_y:None
TextInput:
multiline:False
write_tab:False
id: search_box
size_hint_x:50
on_text_validate: addlocationform.search_location()
Button:
text:'Search'
size_hint_x:25
on_press: addlocationform.search_location()
Button:
text:'Current Location'
size_hint_x:25
ListView:
id: search_results_list
adapter:
ListAdapter(data=[],cls=ListItemButton)
答案 1 :(得分:0)
您可以通过为其提供ID来访问AddLocationForm
试试这样:
AddLocationForm:
id: form
然后你就可以访问它了:
BoxLayout:
height: '48dp'
size_hint_y:None
TextInput:
multiline:False
write_tab:False
id: search_box
size_hint_x:50
on_text_validate: form.search_location()
Button:
text:'Search'
size_hint_x:25
on_press: form.search_location()