可恶,琢磨了好久,今天终于给他干出来了!
代码
官方示例
这个是获取地理信息的……
http://api.openweathermap.org/geo/1.0/direct?q={city name},{state code},{country code}&limit={limit}&appid={API key}
q
必填 城市名称、州代码(仅适用于美国)和国家/地区代码,用逗号分隔。请使用 ISO 3166 个国家/地区代码。
appid
必填 您唯一的 API 密钥(您始终可以在帐户页面上的“API 密钥”选项卡下找到它)
limit
自选 API 响应中的位置数(API 中最多可以返回 5 个结果 响应)
代码
依赖的第三方库
pip install requests
pip install tkinter
至于剩下的,看运气吧,有的话不管。
Python代码
import requests
import json
import datetime
import time
import tkinter as tk
from tkinter import ttk, messagebox
color = '#FFFFFF'
def show():
jd_label = tk.Label(window,
text='Fake进度条',
font=(r'C:\Windows\Fonts\msyh.ttc', 10),
fg='#000000',
bg=color,
compound='center')
jd_label.place(relx=0.5, rely=0.8, anchor='center')
# 进度条
progressbarOne = tk.ttk.Progressbar(window, length=s_width / 2, orient=tk.HORIZONTAL)
progressbarOne.pack(side=tk.LEFT)
progressbarOne.place(rely=0.85)
# 样式设置
s = tk.ttk.Style()
s.theme_use('winnative') # clam, alt, default, classic, vista, aqua, xpnative, winnative
# 进度值最大值
progressbarOne['maximum'] = 100
# 进度值初始值
progressbarOne['value'] = 0
for i in range(1, 101):
progressbarOne['value'] = i
# 更新画面
window.update()
time.sleep(0.005)
def get_data():
show()
language = 'zh_cn' # 简体中文 &lang={language}
city_name = get_city.get() # q={city_name}
# limit = 5 # &limit={limit}
API_key = get_api.get() # &appid={API_key}
# api_name = 'api' # 好像没什么用
url = f'http://api.openweathermap.org/data/2.5/weather?q={city_name}&units=metric&appid={API_key}&lang={language}'
# 获取数据并转换
target = requests.get(url)
content = target.json()
s = json.dumps(content, ensure_ascii=False, indent=2)
data = json.loads(s)
# 气象数据
city = data["name"]
weather = data["weather"][0]["main"] # Clouds
weather_description = data["weather"][0]["description"] # 多云
temp = data['main']['temp'] # ℃
pressure = data['main']['pressure'] # Pa
humidity = data['main']['humidity'] # %
visibility = data['visibility'] # m
sunrise = trans_time(data['sys']['sunrise'])
sunset = trans_time(data['sys']['sunset'])
x = {'city': city, 'weather': weather, 'weather_description': weather_description, 'temp': temp,
'pressure': pressure, 'humidity': humidity, 'visibility': visibility, 'sunrise': sunrise, 'sunset': sunset}
show_main(x)
# 时间
def trans_time(timestamp: int):
ti = datetime.datetime.fromtimestamp(timestamp).strftime('%H:%M:%S') # '%Y-%m-%d %H:%M:%S'
return ti
def get_time():
time2 = time.strftime('%Y-%m-%d %H:%M:%S')
clock = tk.Label(window, text=time2, font=20, bg=color, fg='#EB3324')
clock.place(relx=0.01, rely=0.935)
clock.after(1000, get_time) # 1000ms=1s
def show_main(infor: dict):
c, w, wd, tp, p, h, v, sr, st = infor.values()
main_text = f'城市:{c}\n天气:{w} {wd}\n温度:{tp} ℃\n湿度:{h} %\n气压:{p} Pa\n能见度:{v} m\n日出:{sr}\n日落:{st}'
tk.messagebox.showinfo(title='获取到的天气信息', message=main_text)
if __name__ == '__main__':
# tk.messagebox.showinfo(title='使用门槛', message='您需要在一个叫openweather的平台注册账号后获取API才能使用'
# '\n这是一个可以上网的程序,如果您担心安全问题,请终止运行')
window = tk.Tk()
s_width, s_height = window.winfo_screenwidth(), window.winfo_screenheight()
size = f'{int(s_width / 2)}x{int(s_height / 2)}+{int(s_width / 4)}+{int(s_height / 4)}'
window.geometry(size)
window.title('Weather')
window.config(background=color)
# window.overrideredirect(True)
window.resizable(False, False)
# 城市
get_city = tk.StringVar()
cc1 = tk.Entry(window, width=30, textvariable=get_city)
cc1.delete(0, 'end')
cc1.insert(0, 'Chengdu')
label1 = tk.Label(window,
text='城市',
font=(r'C:\Windows\Fonts\msyh.ttc', 15),
fg='#000000',
bg=color,
compound='center')
label1.place(relx=0.2, rely=0.3)
cc1.place(relx=0.4, rely=0.3)
# API
get_api = tk.StringVar()
cc2 = tk.Entry(window, width=30, textvariable=get_api)
cc2.delete(0, 'end')
cc2.insert(0, '')
label2 = tk.Label(window,
text='您的API',
font=(r'C:\Windows\Fonts\msyh.ttc', 15),
fg='#000000',
bg=color,
compound='center')
label2.place(relx=0.2, rely=0.4)
cc2.place(relx=0.4, rely=0.4)
btu = tk.Button(window,
text='开始',
fg="#000000",
width=7,
compound='center',
bg=color,
command=get_data).place(relx=0.5, rely=0.6, anchor='center')
get_time()
window.mainloop()
部分解释
语言
英语: en
中文简体: zh_cn
中文繁体: zh_tw
法语: fr
德语: de
日语: ja
韩语: kr
西班牙语: es
俄语: ru
土耳其语: tr
越南语: vi
字典内信息
json版的比较易读
{
"coord": {
"lon": 104.0667,
"lat": 30.6667
},
"weather": [
{
"id": 802,
"main": "Clouds",
"description": "多云",
"icon": "03n"
}
],
"base": "stations",
"main": {
"temp": 27.94,
"feels_like": 28.75,
"temp_min": 27.94,
"temp_max": 27.94,
"pressure": 1006,
"humidity": 54
},
"visibility": 10000,
"wind": {
"speed": 2,
"deg": 210
},
"clouds": {
"all": 40
},
"dt": 1719066518,
"sys": {
"type": 1,
"id": 9674,
"country": "CN",
"sunrise": 1719007305,
"sunset": 1719058179
},
"timezone": 28800,
"id": 1815286,
"name": "Chengdu",
"cod": 200
}
dict版
'''
{'coord': {'lon': 104.0667, 'lat': 30.6667}, 'weather': [{'id': 802, 'main': 'Clouds', 'description': '多云',
'icon': '03n'}], 'base': 'stations', 'main': {'temp': 27.94, 'feels_like': 28.75, 'temp_min': 27.94, 'temp_max':
27.94, 'pressure': 1006, 'humidity': 54}, 'visibility': 10000, 'wind': {'speed': 2, 'deg': 210}, 'clouds': {'all':
40}, 'dt': 1719065933, 'sys': {'type': 1, 'id': 9674, 'country': 'CN', 'sunrise': 1719007305, 'sunset': 1719058179},
'timezone': 28800, 'id': 1815286, 'name': 'Chengdu', 'cod': 200}
<class 'dict'>
'''
只想学怎么调用的看这里
如何调用数据参考上面的“字典内信息”
language = 'zh_cn' # 简体中文 &lang={language}
city_name = get_city.get() # q={city_name}
# limit = 5 # &limit={limit}
API_key = get_api.get() # &appid={API_key}
# api_name = 'api' # 好像没什么用
url = f'http://api.openweathermap.org/data/2.5/weather?q={city_name}&units=metric&appid={API_key}&lang={language}'
target = requests.get(url)
content = target.json()
s = json.dumps(content, ensure_ascii=False, indent=2)
data = json.loads(s)
# 气象数据
city = data["name"]
weather = data["weather"][0]["main"] # Clouds
weather_description = data["weather"][0]["description"] # 多云
temp = data['main']['temp'] # ℃
pressure = data['main']['pressure'] # Pa
humidity = data['main']['humidity'] # %
visibility = data['visibility'] # m
sunrise = trans_time(data['sys']['sunrise'])
sunset = trans_time(data['sys']['sunset'])
x = {'city': city, 'weather': weather, 'weather_description': weather_description, 'temp': temp,'pressure': pressure, 'humidity': humidity, 'visibility': visibility, 'sunrise': sunrise, 'sunset': sunset}
你可以分别print一下看看效果或者分步学习
本程序实现效果
主界面
获取到的数据