使用Python擷取各個城市當前的天氣情況

來源:互聯網
上載者:User

標籤:Python   天氣   tkinter   

這次的這個項目,弄了好幾天,主要在tkinter上做GUI介面上一直卡住,在網上資料又不多,最後直接放棄稍微複雜的東西,直接做個簡單點的介面。

程式功能:

1、可以查詢不同城市的天氣情況和顯示時間,每60秒重新整理次天氣情況,

2、可以自由選擇城市,選擇之後立刻擷取該城市的天氣情況

關鍵代碼
# _*_ coding: utf-8 _*_import requestsimport timedef 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庫。

思考與總結
  • 本次項目更多的坑是在tkinter的使用上,真是tkinter從入門到放棄。不過也瞭解tkinter的一些運行機制,瞭解tkinter的三種布局方式,pack(),place(),grid(),此次主演用到的是place()。
  • 使用了Python的多線程,分別是用來控制視窗的主線程、控制時間的子線程和控制天氣更新的子線程。
  • 學習使用了sleep.time()隔段時間來更新天氣情況。
  • 不過此次小項目主要的思想還是面向過程的,代碼想到哪就寫到哪,沒有個合理的規劃。
  • 對於物件導向的編程還是很不熟,接下來要往這方面去學習。本次項目的源碼:http://down.51cto.com/data/2444907

使用Python擷取各個城市當前的天氣情況

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.