How to get the current weather data and display it on the GUI while updating it automatically

0. First

If you want to see how the things you make this time work, please see here (youtube video).

1. OpenWeatherMap API settings

First, access OpenWeatherMap here. w1.png Then, when you log in, a screen like this will be displayed, so go to the API above it. Polish_20200613_071205710.png Then, to get the current weather data, press Subscribe in Currbnt Weather Data. Polish_20200613_070919098.png Then press Free's Get API Key. Polish_20200613_071312064.png Then you will be taken to the first screen, so press API Keys. Polish_20200613_071018224.png Then you can see the obtained API Key. w6.png

2. Acquisition of meteorological data

get_weather_data.py


import requests
import json
import schedule

api_key = '8c5752202e9c558f8d76310d5d96ee03'
city_name = 'Tokyo'
url = f'http://api.openweathermap.org/data/2.5/weather?q={city_name}&appid={api_key}&lang=ja'
response = requests.get(url)

def show_data():
    response = requests.get(url)
    data = json.loads(response.text)
    print(data)

#data['weather'][0]['description']

If you execute show_data (), you will get the following Json data. You can get the result in Japanese by adding lang = ja at the end of the url.

{'coord': {'lon': 139.69, 'lat': 35.69}, 'weather': [{'id': 500, 'main': 'Rain', 'description': 'light rain', 'icon': '10d'}], 'base': 'stations', 'main': {'temp': 293.2, 'feels_like': 294.56, 'temp_min': 292.15, 'temp_max': 294.26, 'pressure': 1008, 'humidity': 93}, 'visibility': 7000, 'wind': {'speed': 2.6, 'deg': 80}, 'rain': {'1h': 0.64}, 'clouds': {'all': 75}, 'dt': 1589781754, 'sys': {'type': 1, 'id': 8077, 'country': 'JP', 'sunrise': 1589744047, 'sunset': 1589794888}, 'timezone': 32400, 'id': 1850144, 'name': 'Tokyo', 'cod': 200}

3. GUI settings to display

weather.py


import requests
import json
import datetime
import tkinter as tk

class Weather:
    def __init__(self,parent):
        self.api_key = '2d3e148162f779382b38d219e60e028e'
        self.city_name = 'Tokyo'
        self.url = f"http://api.openweathermap.org/data/2.5/weather?q={self.city_name}&appid={self.api_key}&lang=ja"

        self.label = tk.Label(parent,text="weather data")
        self.label2 = tk.Label(parent,text="updated time")
        self.label.pack()
        self.label2.pack()
        self.label.after(60000,self.change_info)
        self.label2.after(60000,self.change_info)


    def show_data(self):
        response = requests.get(self.url)
        data = json.loads(response.text)
        print(data['weather'][0]['description'],datetime.datetime.now())
        return data
    
    def change_info(self):
        time = datetime.datetime.now()
        data = self.show_data()
        var = data['weather'][0]['description']
        self.label.configure(text=var)
        self.label2.configure(text=time) 
        self.label.after(60000,self.change_info)
        self.label2.after(60000,self.change_info)
        

#if __name__ == '__main__':
#    root = tk.Tk()
#    weather = Weather(root)
#    root.mainloop()

run = True
while run:
    try:
        root = tk.Tk()
        weather = Weather(root)
        root.mainloop()
    except KeyboardInterrupt:
        run = False

Again, I haven't done anything particularly difficult. Every minute, change_info () is called to get the data and update the GUI label. However, if you do it if you do not comment out when you finish it, it will end at the next update, so improvement is still needed. If you know how to get a good finish, please let me know. Please.

Finally

This method is also explained in Youtube, so please have a look if you like it. If you have any questions, please use the comment section of the video or the comment section of this article. Also, if you like it, please subscribe to the channel.

Recommended Posts

How to get the current weather data and display it on the GUI while updating it automatically
How to return the data contained in django model in json format and map it on leaflet
[Personal memo] Get data on the Web and make it a DataFrame
How to install Git GUI and Gitk on CentOS
I tried to display the time and today's weather w
[Python / Ruby] Understanding with code How to get data from online and write it to CSV
How to get all the keys and values in the dictionary
[Introduction to Python] How to get data with the listdir function
How to get and set the NTP server name by DHCP
How to install OpenCV on Cloud9 and run it in Python
Display the image of the camera connected to the personal computer on the GUI.
How easy is it to synthesize a drug on the market?
How to display PDF resolution and detailed information on Linux (pdfinfo)
How to display bytes in the same way in Java and Python
I tried to push the Sphinx document to BitBucket and it will be automatically reflected on the web server
Upload data to s3 of aws with a command and update it, and delete the used data (on the way)
[Python Kivy] How to get the file path by dragging and dropping
[Python] How to specify the window display position and size of matplotlib
How to divide and process a data frame using the groupby function
How to make only one data register on the Django admin screen
How to display the progress bar (tqdm)
[Rails] How to calculate latitude and longitude with high accuracy using Geocoding API and display it on Google Map
How to display emoji on Manjaro Linux
How to get colored output to the console
How to get started with the 2020 Python project (windows wsl and mac standardization)
How to turn off the scale value display while leaving the grid with matplotlib
How to get the key on Amazon S3 with Boto 3, implementation example, notes
[Python] How to name table data and output it in csv (to_csv method)
I'm addicted to the difference in how Flask and Django receive JSON data
I tried to rescue the data of the laptop by booting it on Ubuntu
How to install Fast.ai on Alibaba Cloud GPU and run it on Jupyter notebook
The first step to log analysis (how to format and put log data in Pandas)
[Introduction to Python] How to get the index of data with a for statement
[Python] How to change the date format (display format)
[Django] How to get data by specifying SQL.
[Python] How to read data from CIFAR-10 and CIFAR-100
How to get article data using Qiita API
How to get the files in the [Python] folder
Data cleaning How to handle missing and outliers
How to install Cascade detector and how to use it
[Rails] How to display multiple markers on Google Map and display a balloon when clicked
[Blender] How to get the selection order of vertices, edges and faces of an object
I tried to understand how to use Pandas and multicollinearity based on the Affairs dataset.
Get the latest schedule from Google Calendar and notify it on LINE every morning
How to find out which process is using the localhost port and stop it