此次的这个项目,弄了好几天,主要在tkinter上作GUI界面上一直卡住,在网上资料又很少,最后直接放弃稍微复杂的东西,直接作个简单点的界面。编程
一、能够查询不一样城市的天气状况和显示时间,每60秒刷新次天气状况,如图:
二、能够自由选择城市,选择以后马上获取该城市的天气状况json
# _*_ coding: utf-8 _*_ import requests import time def weather_log(stu): #获取实时天气状况写入到文本 cu_time=time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) fp=open('weather.log','a') fp.write('{} {}'.format(cu_time,stu)) fp.close() #把文本中城市与城市ID一一对应的关系存进dic字典中 f=open('cityid.txt','r') dic={} for line in f: v=line.strip().split(',') dic[v[1]]=v[0] f.close() def update_weather(city): #经过小米天气API获取天气情况 if city in dic: cityid=dic[city] temp=requests.get("http://weatherapi.market.xiaomi.com/wtr-v2/temp/realtime?cityId="+cityid) temp.encoding='utf-8' tem=temp.json()['weatherinfo']['temp'] SD=temp.json()['weatherinfo']['SD'] w=temp.json()['weatherinfo']['WD']+temp.json()['weatherinfo']['WS'] weather=temp.json()['weatherinfo']['weather'] update_time=temp.json()['weatherinfo']['time'] stu='{0}此刻温度:{1} {2} {3} 天气更新时间:{4}\n'.format(city,tem,weather,w,update_time) weather_log(stu) else : print("请肯定城市是否正确") return (tem,SD,w,weather)
这些只是关键代码,完整代码和cityid文件可在下面的连接中下载。
cityid的文件格式以下图:
关键程序很简单,就是经过cityid这文件生成cityid与城市名对应的字典,再经过小米的天气API去获取该城市的天气信息,请求的地址返回的是json格式的数据,因此直接用requests库中的json的方法访问便可,无需使用标准库的json库。api