此次的這個項目,弄了好幾天,主要在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