Build a Weather Forecast Desktop App with PyQt5 in Minutes

This tutorial walks you through creating a Python desktop weather application using PyQt5, covering environment setup, city code preprocessing with pandas, UI design in Qt Designer, API integration, JSON parsing, shortcut handling, and packaging with PyInstaller.

Python Crawling & Data Mining
Python Crawling & Data Mining
Python Crawling & Data Mining
Build a Weather Forecast Desktop App with PyQt5 in Minutes

Development Environment

Python3

PyQt5

requests

Preparation Work

Download the city‑code CSV from HeWeather , read it with pandas, keep the City_ID and City_CN columns, extract the numeric part of City_ID, build a mapping dictionary, and save it as city_code.txt.

import pandas as pd
# Read the downloaded file named 'city_code.csv'
file = pd.read_csv('city_code.csv')
# Keep only the two needed columns
file = file.loc[:, ['City_ID', 'City_CN']]
# Show the first five rows
file.head()

# Extract numeric part of City_ID
import re

def convert(x):
    pat = re.compile('(\d+)')
    return pat.search(x).group()

file['City_ID_map'] = file['City_ID'].map(convert)

# Build city‑to‑code mapping dictionary

def city2id(file):
    code_dict = {}
    key = 'City_CN'
    value = 'City_ID_map'
    for k, v in zip(file[key], file[value]):
        code_dict[k] = v
    return code_dict

code_dict = city2id(file)

# Save the dictionary to a txt file
import json
filename = 'city_code.txt'
with open(filename, 'w') as f:
    json.dump(code_dict, f)

Later you can load the dictionary with:

with open(filename, 'r') as f:
    text = json.load(f)

UI Design

Design the interface with Qt Designer; the resulting layout looks like the image below.

Main Logic

The API endpoint used is http://wthrcdn.etouch.cn/weather_mini?citykey={code}. Replace {code} with the city code (e.g., 101191101 for Changzhou) and send a GET request. The service returns a JSON payload that can be parsed to extract weather details.

# Extract weather information
city = f"城市:{data['city']}
"
today = data['forecast'][0]
date = f"日期:{today['date']}
"
now = f"实时温度:{data['wendu']}度
"
temperature = f"温度:{today['high']} {today['low']}
"
wind = f"风向:{today['fengxiang']}
"
weather = f"天气:{today['type']}
"
tips = f"贴士:{data['ganmao']}
"

Fetch the JSON with requests.get and handle possible errors:

def query_weather(code):
    # Build request URL
    url = f'http://wthrcdn.etouch.cn/weather_mini?citykey={code}'
    try:
        resp = requests.get(url)
        resp.encoding = 'utf-8'
    except requests.ConnectionError:
        raise
    try:
        info_json = resp.json()
    except JSONDecodeError:
        return '无法查询'
    return info_json

Additional UI Controls

# Set textEdit to read‑only
self.textEdit.setReadOnly(True)
# Focus the lineEdit widget
self.lineEdit.setFocus()
# Get text from lineEdit
city = self.lineEdit.text()
# Set text in textEdit
self.textEdit.setText(info)
# Clear lineEdit
self.lineEdit.clear()

Define a shortcut for the query button by overriding keyPressEvent:

def keyPressEvent(self, e):
    # Trigger query on Enter key
    if e.key() == Qt.Key_Return:
        self.queryWeather()

Packaging

Package the application with PyInstaller:

pyinstaller -w weather.py

After building, copy city_code.txt into the dist/weather folder so the executable can locate the mapping file.

The complete source code and compiled executable can be obtained by replying with the keyword “天气”.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

PythonDesktop ApplicationpandasPyQt5Weather API
Python Crawling & Data Mining
Written by

Python Crawling & Data Mining

Life's short, I code in Python. This channel shares Python web crawling, data mining, analysis, processing, visualization, automated testing, DevOps, big data, AI, cloud computing, machine learning tools, resources, news, technical articles, tutorial videos and learning materials. Join us!

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.