Pré-requisitos: Encontre o clima atual de qualquer cidade usando a API openweathermap

A ideia deste artigo é fornecer um aplicativo GUI simples aos usuários para obter a temperatura atual de qualquer cidade que desejam ver. O sistema também fornece uma interface de usuário simples para simplificar a aplicação. Ele também fornece uma UX incrível para seus usuários. As características deste aplicativo serão que ele será um aplicativo de previsão do tempo em tempo real que retorna a temperatura atual, temperatura máxima e mínima, umidade, latitude e coordenadas de longitude da cidade pesquisada, data atual e hora. Também pode alterar o tema de acordo com a hora do dia.

API Openweathermap

openweathermap é um serviço que fornece dados meteorológicos, incluindo dados meteorológicos atuais, previsões e dados históricos para os desenvolvedores de serviços da web e aplicativos móveis.

Módulos Necessários

  • Tkinter: É a maneira mais rápida e fácil de criar aplicativos GUI. Isso está incluído nos módulos padrão do Python , portanto, não há necessidade de instalá-lo externamente.
  • PIL: PIL é a biblioteca de imagens Python que fornece ao interpretador python recursos de edição de imagens.
  • json: Este módulo é usado para lidar com arquivos JSON e vem integrado com o Python. Portanto, não há necessidade de instalá-lo externamente
  • solicitações: é usado para fazer solicitações HTTP a um URL especificado. Este módulo não vem embutido com Python. Para instalá-lo, digite o comando abaixo no terminal.
pedidos de instalação pip

Imagens usadas no aplicativo abaixo:

moon.png

sun.png

logo.png



Abaixo está a implementação.

  
from tkinter import *
import requests 
import json 
import datetime 
from PIL import ImageTk, Image 
  
  
root = Tk() 
root.title("Weather App") 
root.geometry("450x700") 
root['background'] = "white"
new = ImageTk.PhotoImage(Image.open('logo.png')) 
panel = Label(root, image=new) 
panel.place(x=0, y=520) 
  
  
dt = datetime.datetime.now() 
date = Label(root, text=dt.strftime('%A--'), bg='white', font=("bold", 15)) 
date.place(x=5, y=130) 
month = Label(root, text=dt.strftime('%m %B'), bg='white', font=("bold", 15)) 
month.place(x=100, y=130) 
hour = Label(root, text=dt.strftime('%I : %M %p'), 
             bg='white', font=("bold", 15)) 
hour.place(x=10, y=160) 
if int((dt.strftime('%I'))) >= 8 & int((dt.strftime('%I'))) <= 5: 
    img = ImageTk.PhotoImage(Image.open('moon.png')) 
    panel = Label(root, image=img) 
    panel.place(x=210, y=200) 
else: 
    img = ImageTk.PhotoImage(Image.open('sun.png')) 
    panel = Label(root, image=img) 
    panel.place(x=210, y=200) 
  
  
city_name = StringVar() 
city_entry = Entry(root, textvariable=city_name, width=45) 
city_entry.grid(row=1, column=0, ipady=10, stick=W+E+N+S) 
  
  
def city_name(): 
  
    
    api_request = requests.get("https://api.openweathermap.org/data/2.5/weather?q="
                               + city_entry.get() + "&units=metric&appid="+api_key) 
  
    api = json.loads(api_request.content) 
  
    
    y = api['main'] 
    current_temprature = y['temp'] 
    humidity = y['humidity'] 
    tempmin = y['temp_min'] 
    tempmax = y['temp_max'] 
  
    
    x = api['coord'] 
    longtitude = x['lon'] 
    latitude = x['lat'] 
  
    
    z = api['sys'] 
    country = z['country'] 
    citi = api['name'] 
  
    
    lable_temp.configure(text=current_temprature) 
    lable_humidity.configure(text=humidity) 
    max_temp.configure(text=tempmax) 
    min_temp.configure(text=tempmin) 
    lable_lon.configure(text=longtitude) 
    lable_lat.configure(text=latitude) 
    lable_country.configure(text=country) 
    lable_citi.configure(text=citi) 
  
  
city_nameButton = Button(root, text="Search", command=city_name) 
city_nameButton.grid(row=1, column=1, padx=5, stick=W+E+N+S) 
  
  
lable_citi = Label(root, text="...", width=0
                   bg='white', font=("bold", 15)) 
lable_citi.place(x=10, y=63) 
  
lable_country = Label(root, text="...", width=0
                      bg='white', font=("bold", 15)) 
lable_country.place(x=135, y=63) 
  
lable_lon = Label(root, text="...", width=0, 
                  bg='white', font=("Helvetica", 15)) 
lable_lon.place(x=25, y=95) 
lable_lat = Label(root, text="...", width=0, 
                  bg='white', font=("Helvetica", 15)) 
lable_lat.place(x=95, y=95) 
  
  
lable_temp = Label(root, text="...", width=0, bg='white', 
                   font=("Helvetica", 110), fg='black') 
lable_temp.place(x=18, y=220) 
  
  
humi = Label(root, text="Humidity: ", width=0
             bg='white', font=("bold", 15)) 
humi.place(x=3, y=400) 
  
lable_humidity = Label(root, text="...", width=0, 
                       bg='white', font=("bold", 15)) 
lable_humidity.place(x=107, y=400) 
  
  
maxi = Label(root, text="Max. Temp.: ", width=0
             bg='white', font=("bold", 15)) 
maxi.place(x=3, y=430) 
  
max_temp = Label(root, text="...", width=0
                 bg='white', font=("bold", 15)) 
max_temp.place(x=128, y=430) 
  
  
mini = Label(root, text="Min. Temp.: ", width=0
             bg='white', font=("bold", 15)) 
mini.place(x=3, y=460) 
  
min_temp = Label(root, text="...", width=0
                 bg='white', font=("bold", 15)) 
min_temp.place(x=128, y=460) 
  
  
note = Label(root, text="All temperatures in degree celsius", 
             bg='white', font=("italic", 10)) 
note.place(x=95, y=495) 
  
  
root.mainloop() 

Resultado: