You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
69 lines
2.7 KiB
69 lines
2.7 KiB
import tkinter as tk
|
|
from tkinter import messagebox
|
|
import urllib.request
|
|
import gzip
|
|
import json
|
|
from urllib.parse import quote
|
|
|
|
|
|
def main():
|
|
# 输入窗口
|
|
root = tk.Tk()
|
|
root.title('气象数据分析') # 窗口标题
|
|
|
|
tk.Label(root, text='请输入城市').grid(row=0, column=0) # 设置标签并调整位置
|
|
enter = tk.Entry(root) # 输入框
|
|
enter.grid(row=0, column=1, padx=20, pady=20) # 调整位置
|
|
enter.delete(0, tk.END) # 清空输入框
|
|
enter.insert(0, '北京') # 设置默认文本
|
|
|
|
def get_weather_data():
|
|
city_name = enter.get() # 获取输入框的内容
|
|
url = f'https://data.cma.cn/?spm={quote(city_name)}'
|
|
|
|
try:
|
|
weather_data = urllib.request.urlopen(url).read()
|
|
weather_data = gzip.decompress(weather_data).decode('utf-8')
|
|
weather_dict = json.loads(weather_data)
|
|
|
|
if weather_dict.get('status') != 200:
|
|
messagebox.showerror("错误", "你输入的城市名有误,或者天气中心未收录你所在城市")
|
|
else:
|
|
show_data(weather_dict, city_name)
|
|
except Exception as e:
|
|
messagebox.showerror("错误", f"请求天气数据时发生错误: {e}")
|
|
|
|
def show_data(weather_dict, city_name):
|
|
forecast = weather_dict.get('data').get('forecast')
|
|
|
|
root1 = tk.Toplevel(root) # 使用Toplevel创建子窗口
|
|
root1.geometry('650x280')
|
|
root1.title(city_name + '天气状况')
|
|
|
|
for i in range(5):
|
|
group = tk.LabelFrame(root1, text=f'{forecast[i].get("date")}天气状况', padx=10, pady=10)
|
|
group.pack(padx=10, pady=5, side=tk.TOP, anchor=tk.W)
|
|
|
|
LANGS = [
|
|
('风向', forecast[i].get('fengxiang')),
|
|
('风级', str(forecast[i].get('fengji'))),
|
|
('最高温', forecast[i].get('high')),
|
|
('最低温', forecast[i].get('low')),
|
|
('天气', forecast[i].get('type'))
|
|
]
|
|
for label_text, value in LANGS:
|
|
tk.Label(group, text=f'{label_text}: {value}').pack(anchor=tk.W)
|
|
|
|
tk.Label(root1, text=f'今日{weather_dict.get("data").get("ganmao")}', fg='green').pack(side=tk.TOP, pady=10)
|
|
tk.Label(root1, text="StarMan: 49star.com", fg="green", bg="yellow").pack(side=tk.BOTTOM, pady=10)
|
|
|
|
tk.Button(root1, text='确认并退出', width=10, command=root1.destroy).pack(side=tk.BOTTOM, pady=10)
|
|
|
|
tk.Button(root, text="确认", width=10, command=get_weather_data).grid(row=1, column=0, sticky=tk.W, padx=10, pady=5)
|
|
tk.Button(root, text='退出', width=10, command=root.destroy).grid(row=1, column=1, sticky=tk.E, padx=10, pady=5)
|
|
|
|
root.mainloop()
|
|
|
|
|
|
if __name__ == '__main__':
|
|
main() |