简体   繁体   中英

Python 2.7 Tkinter: loop through labels to display data on new row

I currently trying to create a weather application and I have code that prints out the day, forecast, and maxtemperture for the next 7 days.

weather_req_url = "https://api.forecast.io/forecast/%s/%s,%s?units=uk2" % (weather_api_token, lat,lon)
r = requests.get(weather_req_url)
weather_obj = json.loads(r.text)

t = datetime.now()
for i, x in enumerate(weather_obj["daily"]["data"][1:8]):
    print (t+timedelta(days=i+1)).strftime("\t%a"), x['icon'], ("%.0f" % x['temperatureMax'])

This codes prints this information in the shell:

Sat rain 20
Sun partly-cloudy-day 21
Mon clear-day 26
Tue partly-cloudy-night 29
Wed rain 28
Thu rain 24
Fri rain 23 

I currently have a frame and a label for it however I don't want to manually create a label for each row.

self.degreeFrm = Frame(self, bg="black")
self.degreeFrm.grid(row = 0, column = 0)

self.temperatureLbl = Label(self.degreeFrm, font=('Helvetica Neue UltraLight', 80), fg="white", bg="black")
self.temperatureLbl.grid(row = 0, column = 0, sticky = E)

Is there a way to run the first chunk of code that creates and displays a label with the information from each iteration of the for loop.

As in the comment above, something along these lines should do the trick:

forecasts = []

for i, x in enumerate(weather_obj["daily"]["data"][1:8]):
    forecasts.append((t+timedelta(days=i+1)).strftime("\t%a"), x['icon'], ("%.0f" % x['temperatureMax']))


row_num = 0
for forecast in forecasts:
    l = Label(self.degreeFrm, font=('Helvetica Neue UltraLight', 80), text = forecast)
    l.grid(row = row_num, column = 0, sticky= E)
    row_num +=1

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM