简体   繁体   English

Python 2.7 Tkinter:遍历标签以在新行上显示数据

[英]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. 我目前正在尝试创建一个天气应用程序,并且我的代码可以打印出接下来7天的天气,天气预报和最高气温。

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. 有没有一种方法可以运行用于创建和显示带有for循环的每次迭代信息的标签的第一块代码。

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. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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