Build a Desktop Weather App with Python and PyQt5 – Full Step‑by‑Step Guide

This tutorial walks through creating a desktop weather application with Python 3, PyQt5, and the requests library, covering environment setup, city code data preparation, UI design with Qt Designer, API querying, JSON parsing, widget handling, shortcut keys, and final packaging with PyInstaller.

MaGe Linux Operations
MaGe Linux Operations
MaGe Linux Operations
Build a Desktop Weather App with Python and PyQt5 – Full Step‑by‑Step Guide

Development Environment

Python 3

PyQt5

requests

Preparing City Code Data

Download the city‑code CSV from the HeWeather website, then use pandas to read the file, keep the City_ID and City_CN columns, and extract the numeric part of the ID.

import pandas as pd
# 将下载好的文件命名为 'city_code.csv'
file = pd.read_csv('city_code.csv')
# 选取需要的两列信息
file = file.loc[:,['City_ID', 'City_CN']]
# 读取前五行信息
file.head()

Convert the ID strings to pure numbers, build a mapping dictionary, and store it as city_code.txt for later reuse.

# 匹配 City_ID 中的数字
def convert(x):
    pat = re.compile('(\d+)')
    return pat.search(x).group()

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

# 建立城市与代码之间的映射关系
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)

# 将所得的字典数据存储为 txt 文件
import json
filename = 'city_code.txt'
with open(filename, 'w') as f:
    json.dump(code_dict, f)

Loading the dictionary later is straightforward:

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

UI Design

The interface is created with Qt Designer; the resulting window includes a line edit for the city name, a read‑only text edit for output, and a query button.

Main Logic – Querying the Weather API

The application calls the public API http://wthrcdn.etouch.cn/weather_mini?citykey={code}, where {code} is the numeric city identifier obtained earlier. The response is JSON.

def query_weather(code):
    # 模板网页
    html = f'http://wthrcdn.etouch.cn/weather_mini?citykey={code}'
    # 向网页发起请求
    try:
        info = requests.get(html)
        info.encoding = 'utf-8'
    except requests.ConnectionError:
        raise
    # 将获取的数据转换为 json 格式
    try:
        info_json = info.json()
    except JSONDecodeError:
        return '无法查询'
    # 提取需要的天气信息
    data = info_json['data']
    city = f"城市:{data['city']}
"
    today = data['forecast'][0]
    date = f"日期:{today['date']}
"
    now = f"实时温度:{data['wendu']}度
"
    temperature = f"温度:{today['high']} {today['low']}
"
    fengxiang = f"风向:{today['fengxiang']}
"
    type = f"天气:{today['type']}
"
    tips = f"贴士:{data['ganmao']}
"
    return city + date + now + temperature + fengxiang + type + tips

Widget Methods Used

self.textEdit.setReadOnly(True)
self.lineEdit.setFocus()
city = self.lineEdit.text()
self.textEdit.setText(info)
self.lineEdit.clear()

Shortcut Key for Query

def keyPressEvent(self, e):
    # 设置快捷键
    if e.key() == Qt.Key_Return:
        self.queryWeather()

Packaging the Application

After the program works, package it with pyinstaller -w weather.py. Remember to copy city_code.txt into the dist/weather folder so the executable can locate the city‑code dictionary.

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.

GUIPythondata-processingPyQt5Weather APIQt Designer
MaGe Linux Operations
Written by

MaGe Linux Operations

Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.

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.