Python和Root Widgets

时间:2014-06-21 20:35:21

标签: python python-2.7 user-interface kivy

我是一名德国学生,正在努力学习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中而不是在根类中的函数。 我尝试了以下步骤:

  • on_press:app.AddLocationForm.search_location()
  • on_press:AddLocationForm.serach_location()

他们都没有奏效。根据作者的说法,它必须调用&#34; root.search_location()&#34;。

有没有人有想法?

1 个答案:

答案 0 :(得分:1)

这本书错了。您可以通过以下方式修复它:

  1. 在kv
  2. id: location_form下添加AddLocationForm
  3. 致电location_form.search_location()
  4. 此外:

    • 在此示例中,root引用WeatherRoot
    • 在您的测试中,您的应用中没有AddLocationForm属性,因此app.AddLocationForm无法正常工作。
    • 在测试中,您尝试直接使用AddLocationForm。这只是一个类,而不是实例。我们无法知道您想要引用哪个实例。

    我想作者首先在下面编写小部件,并将内容移动到,这会破坏一些事情:)