執行效果如下:
from tkinter import * import urllib.request import gzip import json from tkinter import messagebox root = Tk() def main(): # 輸入窗口 root.title('Python學習交流群:973783996') # 窗口標題 Label(root, text='請輸入城市').grid(row=0, column=0) # 設置標簽并調整位置 enter = Entry(root) # 輸入框 enter.grid(row=0, column=1, padx=20, pady=20) # 調整位置 enter.delete(0, END) # 清空輸入框 enter.insert(0, 'Python學習交流群:973783996') # 設置默認文本 # enter_text = enter.get()#獲取輸入框的內容 running = 1 def get_weather_data(): # 獲取網站數據 city_name = enter.get() # 獲取輸入框的內容 url1 = 'http://wthrcdn.etouch.cn/weather_mini?city=' + urllib.parse.quote(city_name) url2 = 'http://wthrcdn.etouch.cn/weather_mini?citykey=101010100' # 網址1只需要輸入城市名,網址2需要輸入城市代碼 # print(url1) weather_data = urllib.request.urlopen(url1).read() # 讀取網頁數據 weather_data = gzip.decompress(weather_data).decode('utf-8') # 解壓網頁數據 weather_dict = json.loads(weather_data) # 將json數據轉換為dict數據 if weather_dict.get('desc') == 'invilad-citykey': print(messagebox.askokcancel("xing", "你輸入的城市名有誤,或者天氣中心未收錄你所在城市")) else: # print(messagebox.askokcancel('xing','bingguo')) show_data(weather_dict, city_name) def show_data(weather_dict, city_name): # 顯示數據 forecast = weather_dict.get('data').get('forecast') # 獲取數據塊 root1 = Tk() # 副窗口 root1.geometry('650x280') # 修改窗口大小 root1.title(city_name + '天氣狀況') # 副窗口標題 # 設置日期列表 for i in range(5): # 將每一天的數據放入列表中 LANGS = [(forecast[i].get('date'), '日期'), (forecast[i].get('fengxiang'), '風向'), (str(forecast[i].get('fengji')), '風級'), (forecast[i].get('high'), '最高溫'), (forecast[i].get('low'), '最低溫'), (forecast[i].get('type'), '天氣')] group = LabelFrame(root1, text='天氣狀況', padx=0, pady=0) # 框架 group.pack(padx=11, pady=0, side=LEFT) # 放置框架 for lang, value in LANGS: # 將數據放入框架中 c = Label(group, text=value + ': ' + lang) c.pack(anchor=W) Label(root1, text='今日' + weather_dict.get('data').get('ganmao'), fg='green').place(x=40, y=20, height=40) # 溫馨提示 Label(root1, text="StarMan: 49star.com", fg="green", bg="yellow").place(x=10, y=255, width=125, height=20) # 作者網站 Button(root1, text='確認并退出', width=10, command=root1.quit).place(x=500, y=230, width=80, height=40) # 退出按鈕 root1.mainloop() # 布置按鍵 Button(root, text="確認", width=10, command=get_weather_data) \ .grid(row=3, column=0, sticky=W, padx=10, pady=5) Button(root, text='退出', width=10, command=root.quit) \ .grid(row=3, column=1, sticky=E, padx=10, pady=5) if running == 1: root.mainloop() if __name__ == '__main__': main()
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
