气象信息API
用WPF技术搭建简单的气象免费小控件,注册取得key
前端代码:
<Grid> <Grid.ColumnDefinitions> <ColumnDefinition Width="611*"/> <ColumnDefinition Width="189*"/> </Grid.ColumnDefinitions> <StackPanel Margin="10,10,10,10" Grid.ColumnSpan="2"> <TextBlock Text="输入城市:"/> <TextBox x:Name="txtCity" Width="200"/> <Button Width="200" Content="取得天气" Click="btnGetWeather_Click" Margin="0,10,10,10"/> <TextBlock Text="气象信息:" Margin="0,20,0,0" /> <TextBlock x:Name="txtqixiangxinxi"/> </StackPanel> </Grid>
后端逻辑
public partial class MainWindow : Window { private const string ApiKey = "key"; private const string ApiBaseUrl = "https://api.openweathermap.org/data/2.5/weather"; public MainWindow() { InitializeComponent(); } private async void btnGetWeather_Click(object sender, RoutedEventArgs e) { string city = txtCity.Text; string apiUrl = $"{ApiBaseUrl}?q={city}&appid={ApiKey}"; try { HttpClient httpClient = new HttpClient(); HttpResponseMessage response = await httpClient.GetAsync(apiUrl); response.EnsureSuccessStatusCode(); string responseBody = await response.Content.ReadAsStringAsync(); // 解析 JSON 数据,提取天气信息 // 这里需要根据您选择的 API 和其返回的数据结构进行解析 // 示例:从 OpenWeatherMap API 中提取温度信息 dynamic weatherData = JsonConvert.DeserializeObject(responseBody); double temperature = weatherData.main.temp - 273.15; // 转换为摄氏度 txtqixiangxinxi.Text = $"Temperature in {city}: {temperature}°C"; } catch (Exception ex) { MessageBox.Show($"Error: {ex.Message}"); } } }
Weather Conditions - OpenWeatherMap
from tkinter import * import requests import json from datetime import datetime root =Tk() root.geometry("400x400") root.resizable(0,0) root.title("天气预报") city_value = StringVar() def time_format_for_location(utc_with_tz): local_time = datetime.utcfromtimestamp(utc_with_tz) return local_time.time() def showWeather(): #Enter you api key, copies from the OpenWeatherMap dashboard api_key = "key" #sample API # Get city name from user from the input field (later in the code) city_name=city_value.get() # API url weather_url = 'http://api.openweathermap.org/data/2.5/weather?q=' + city_name + '&appid='+api_key # Get the response from fetched url response = requests.get(weather_url) # changing response from json to python readable weather_info = response.json() print(weather_info) if weather_info['cod'] == 200: kelvin = 273 # value of kelvin temp = int(weather_info['main']['temp'] - kelvin) #converting default kelvin value to Celcius feels_like_temp = int(weather_info['main']['feels_like'] - kelvin) pressure = weather_info['main']['pressure'] humidity = weather_info['main']['humidity'] wind_speed = weather_info['wind']['speed'] * 3.6 sunrise = weather_info['sys']['sunrise'] sunset = weather_info['sys']['sunset'] timezone = weather_info['timezone'] cloudy = weather_info['clouds']['all'] description = weather_info['weather'][0]['description'] sunrise_time = time_format_for_location(sunrise + timezone) sunset_time = time_format_for_location(sunset + timezone) weather = f"\nWeather of: {city_name}\nTemperature (Celsius): {temp}°\nFeels like in (Celsius): {feels_like_temp}°\nPressure: {pressure} hPa\nHumidity: {humidity}%\nSunrise at {sunrise_time} and Sunset at {sunset_time}\nCloud: {cloudy}%\nInfo: {description}" else: weather = f"\n\tWeather for '{city_name}' not found!\n\tKindly Enter valid City Name !!" tfield.delete("1.0", "end") tfield.insert(INSERT, weather) #to insert or send value in our Text Field to display output Label(root, text = '输入城市名称:', font = 'Arial 12 bold').pack(pady=10) #to generate label heading Entry(root, textvariable = city_value, width = 24, font='Arial 14 bold').pack() Button(root, command = showWeather, text = "获取天气数据", font="Arial 10", bg='lightblue', fg='black', activebackground="teal", padx=5, pady=5 ).pack(pady= 20) Label(root, text = "今天天气:", font = 'arial 12 bold').pack(pady=10) tfield = Text(root, width=46, height=10) tfield.pack() root.mainloop()
,Best Wish 不负年华