2014-10-04 2 views
0

Хорошо, я заполняю список с помощью listitembuttons на основе поиска городов. Он заполнит список списком для каждого города, который соответствует введенному тексту. Когда я вхожу в новый город, я хочу удалить другие listitembuttons и заменить их новым списком городов, которые я искал. Я могу удалить их, используя этот фрагмент кода.Удаление ListItemButtons из виджета виджета kivy

def clear_locations(self): 
     for x in self.search_results.adapter.data: 
      self.search_results.adapter.data.remove(x) 

Если я использую эту функцию для печати х I N self.search_results.adapter.data: например, когда я искал Лондон: он напечатает четыре города, каждый в своем собственном ListItemButton. Однако он удаляет только количество ListItemButtons, равное количеству новых.

Скажем, сначала я ищу лондон и получаю четыре списка. Затем я ищу пари. Он удаляет два из лондонских listitembuttons и добавляет два paris. Если я буду искать murfreesboro, он удалит один из лондонских listitembuttons и добавит один murfreesboro. То, чего я не понимаю, состоит в том, что четыре цикла пройдут и распечатают все города в данных, но будут удалять только сумму, равную количеству новых городов. Любая помощь будет большой.

вот остальная часть моего кода: main.py

from kivy.app import App 
from kivy.uix.boxlayout import BoxLayout 
from kivy.properties import ObjectProperty, ListProperty, StringProperty, NumericProperty 
from kivy.network.urlrequest import UrlRequest 
import json 
from kivy.adapters.listadapter import ListAdapter 
from kivy.uix.listview import ListItemButton 

class WeatherRoot(BoxLayout): 

    location_form = ObjectProperty() 
    current_weather = ObjectProperty() 

    def show_current_weather(self, location=None): 
     self.clear_widgets() 

     if location is not None: 
      self.current_weather = CurrentWeather(location=location) 

     if self.current_weather is None: 
      self.current_weather = CurrentWeather() 

     if location is None: 
      self.current_weather.location = location 

     self.current_weather.update_weather()  
     self.add_widget(self.current_weather) 

    def add_location(self): 
     self.clear_widgets() 
     self.add_widget(self.location_form) 

class CurrentWeather(BoxLayout): 
    location = ListProperty(["NewYork", "US"]) 
    conditions = StringProperty() 
    temp = NumericProperty() 
    temp_min = NumericProperty() 
    temp_max = NumericProperty() 
    wind = NumericProperty() 
    humidity = NumericProperty() 

    def update_weather(self): 
     weather_template = "http://api.openweathermap.org/data/2.5/weather?q={},{}&units=imperial&APID=a1bf58ef2e81e600af117e12e13e0ff1" 
     weather_url = weather_template.format(*self.location) 
     request = UrlRequest(weather_url, self.weather_retrieved) 

    def weather_retrieved(self, request, data): 
     self.conditions = data['weather'][0]['description'] 
     self.temp = data['main']['temp'] 
     self.temp_min = data['main']['temp_min'] 
     self.temp_max = data['main']['temp_max'] 
     self.wind = data['wind']['speed'] 
     self.humidity = data['main']['humidity'] 

class LocationButton(ListItemButton): 
    location = ListProperty() 

class AddLocationForm(BoxLayout): 

    search_input = ObjectProperty() 
    search_results = ObjectProperty() 

    def args_converter(self, index, data_item): 
     (city, country) = data_item 
     return {'location':(city,country)} 

    def web_error(self, *args, **kwargs): 
     self.search_results.data = ["Either the openweather.org is down", "or you are not connected to the interweb"] 

    def clear_locations(self): 
     for x in self.search_results.adapter.data: 
      self.search_results.adapter.data.remove(x) 


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


    def found_location(self, request, data): 
     try: 
      cities = [(d['name'], d['sys']['country']) for d in data['list']] 
     except: 
      cities = ["No", "Citys Found"] 
     self.search_results.adapter.data[:] 
     self.search_results.adapter.data.extend(cities) 
     self.search_results._trigger_reset_populate() 



class WeatherApp(App): 
    pass 

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

weather.kv

#: import main main 
#: import ListAdapter kivy.adapters.listadapter.ListAdapter 

WeatherRoot: 


<WeatherRoot>: 
    location_form: add_location_form 
    AddLocationForm: 
     id: add_location_form 

<LocationButton>: 
    text: "{}({})".format(self.location[0], self.location[1]) 
    size_hint_y: None 
    height: "40dp" 
    color: [1, 1, 1, 1] 
    deselected_color: 0,.8,.5,1 
    on_press: app.root.show_current_weather(self.location) 

<CurrentWeather>: 
    orientation: 'vertical' 
    Label: 
     text: "{}({})".format(root.location[0], root.location[1]) 
    Label: 
     text: root.conditions 
    Label: 
     text: "Current Temp: {}".format(root.temp) 
    Label: 
     text: "Low: {}".format(root.temp_min) 
    Label: 
     text: "High: {}".format(root.temp_max) 
    Label: 
     text: "Wind Speed: {}".format(root.wind) 
    Label: 
     text: "Humiditity: {}".format(root.humidity) 
    BoxLayout: 
     orientation: 'horizontal' 
     size_hint_y: None 
     height: "40dp" 
     Button: 
      text: "Add Location" 
      on_press: app.root.add_location() 
     Button: 
      text: "Forcast" 

<AddLocationForm>: 
    orientation: 'vertical' 
    search_input: search_box 
    search_results: search_results_list 
    BoxLayout: 
     size_hint_y: None 
     height: "40dp" 
     TextInput: 
      id: search_box 
      focus: True 
      multiline: False 
      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 = main.LocationButton, args_converter = root.args_converter) 

Так что, если я использую цикл для печати х в self.search_results.adapter. данные во время поиска paris после поиска в Лондоне Я получаю это в консоли:

(u'London', u'CA') 
(u'London', u'GB') 
(u'London Borough of Harrow', u'GB') 
(u'Londonderry County Borough', u'GB') 

B ut, если я использую remove (x) для x в self.search_results.adapter.data: тогда я получаю это при поиске paris после поиска лондона: enter image description here

+0

Очевидно, что вы работаете с книгой Дасти Филлипс, как я, тоже :-). Если вам интересно, как удалить SELECTED ListItemButton, посмотрите мой пост здесь: http://stackoverflow.com/questions/25981827/python-kivy-listview-how-to-delete-selected-listitembutton – barrios

ответ

0

ОБНОВЛЕНИЕ! Нашел отличное решение!

Если кто-то имеет эту проблему, я решил его с

def clear_locations(self): 
    del self.search_results.adapter.data[:] 
Смежные вопросы