PYQT實戰:天氣助手

?? ? ? ?應用采用了現代化的界面設計,包括圓角邊框、卡片式布局和響應式建議功能。

????????這個天氣應用可以作為學習PyQt5開發的實例,展示了GUI設計、定時更新、數據處理和用戶交互的實現方法

#!/usr/bin/env python
# -*- coding: GBK -*-
import sys
import requests
from PyQt5.QtWidgets import (QApplication, QMainWindow, QWidget, QLabel, QLineEdit, QPushButton, QVBoxLayout, QHBoxLayout,QFormLayout, QFrame, QGroupBox)
from PyQt5.QtCore import Qt, QDate, QTime, QTimer
from PyQt5.QtGui import QFont, QIcon, QPixmap, QColor, QLinearGradient, QPainterclass App(QMainWindow):def __init__(self):super().__init__()self.setWindowTitle("TianQi Pro 2025")self.setGeometry(300, 200, 650, 500)self.setStyleSheet("background-color: #f0f5ff;")# 主部件main_widget = QWidget()main_layout = QVBoxLayout()# 頂部標題欄title_frame = QFrame()title_frame.setStyleSheet("background-color: #1e88e5; color: white; border-radius: 10px;")title_layout = QHBoxLayout(title_frame)self.title_label = QLabel("天氣助手")self.title_label.setFont(QFont("Microsoft YaHei", 18, QFont.Bold))title_layout.addWidget(self.title_label, 0, Qt.AlignCenter)self.date_label = QLabel()self.date_label.setFont(QFont("Arial", 10))self.update_datetime()title_layout.addWidget(self.date_label, 0, Qt.AlignRight | Qt.AlignVCenter)# 主內容區域content_group = QGroupBox("城市天氣查詢")content_group.setFont(QFont("Microsoft YaHei", 12))content_layout = QFormLayout()# 城市輸入區域city_layout = QHBoxLayout()self.city_input = QLineEdit()self.city_input.setPlaceholderText("輸入城市名稱...")self.city_input.setStyleSheet("padding: 8px; border-radius: 5px;")city_layout.addWidget(self.city_input)self.search_btn = QPushButton("查詢天氣")self.search_btn.setStyleSheet("background-color: #42a5f5; color: white; padding: 8px; border-radius: 5px;")self.search_btn.clicked.connect(self.fetch_weather)city_layout.addWidget(self.search_btn)# 天氣展示區域self.weather_frame = QFrame()self.weather_frame.setStyleSheet("""background-color: #e3f2fd;border-radius: 10px;padding: 15px;""")self.weather_layout = QVBoxLayout(self.weather_frame)# 默認內容default_label = QLabel("請輸入城市名稱并點擊查詢按鈕")default_label.setAlignment(Qt.AlignCenter)self.weather_layout.addWidget(default_label)# 添加到主布局content_layout.addRow(city_layout)content_layout.addRow(self.weather_frame)content_group.setLayout(content_layout)# AI建議區域self.ai_frame = QFrame()self.ai_frame.setStyleSheet("""background-color: #bbdefb;border-radius: 10px;padding: 15px;margin-top: 20px;""")ai_layout = QVBoxLayout(self.ai_frame)self.ai_label = QLabel("助手建議:")self.ai_label.setFont(QFont("Microsoft YaHei", 10))ai_layout.addWidget(self.ai_label)self.ai_content = QLabel("根據當前天氣為您提供出行和著裝建議")self.ai_content.setWordWrap(True)ai_layout.addWidget(self.ai_content)# 組裝主布局main_layout.addWidget(title_frame)main_layout.addWidget(content_group)main_layout.addWidget(self.ai_frame)# 配置布局main_widget.setLayout(main_layout)self.setCentralWidget(main_widget)# 創建計時器更新時間self.timer = QTimer(self)self.timer.timeout.connect(self.update_datetime)self.timer.start(60000)  # 每分鐘更新一次# 默認城市(可選)# self.city_input.setText("北京")# self.fetch_weather()def update_datetime(self):"""更新日期和時間顯示"""current_date = QDate.currentDate().toString("yyyy年MM月dd日")current_time = QTime.currentTime().toString("hh:mm")weekday = ["周一", "周二", "周三", "周四", "周五", "周六", "周日"][QDate.currentDate().dayOfWeek()-1]self.date_label.setText(f"{current_date} {weekday} {current_time}")self.date_label.setFont(QFont("Microsoft YaHei", 10))def fetch_weather(self):"""獲取天氣信息(模擬數據,實際使用時連接真實API)"""city = self.city_input.text().strip()if not city:return# 實際開發時應替換為真實API調用,例如:# api_key = "YOUR_API_KEY"# url = f"https://api.weatherapi.com/v1/current.json?key={api_key}&q={city}"# 這里使用模擬數據weather_data = {"location":city,"temp_c":28,"humidity":65,"wind_kph":12,"condition":"晴","feelslike_c":30}self.display_weather(weather_data)def display_weather(self, data):"""顯示天氣信息"""# 清除舊內容for i in reversed(range(self.weather_layout.count())): self.weather_layout.itemAt(i).widget().setParent(None)# 創建天氣顯示控件# 修改display_weather方法中的城市顯示location_label = QLabel(u"\U0001F4CD {} ".format(data['location']))location_label.setFont(QFont('Microsoft YaHei', 14, QFont.Bold))# 在display_weather方法中temp_label = QLabel(u"\U0001F321 溫度: {}°C (體感 {}°C)".format(data['temp_c'], data['feelslike_c']))condition_label = QLabel(u"\u2601 天氣: {}".format(data['condition']))humidity_label = QLabel(u"\U0001F4A7 濕度: {}%".format(data['humidity']))wind_label = QLabel(u"\U0001F343 風速: {} km/h".format(data['wind_kph']))temp_label.setFont(QFont("Arial", 12))condition_label.setFont(QFont("Arial", 12))humidity_label.setFont(QFont("Arial", 12))wind_label.setFont(QFont("Arial", 12))# 添加天氣圖標(實際應用中根據天氣狀況選擇)pixmap = QPixmap("sunny.png").scaled(64, 64, Qt.KeepAspectRatio)icon_label = QLabel()icon_label.setPixmap(pixmap)icon_label.setAlignment(Qt.AlignCenter)# 添加布局self.weather_layout.addWidget(location_label)self.weather_layout.addWidget(icon_label, alignment=Qt.AlignCenter)self.weather_layout.addWidget(temp_label)self.weather_layout.addWidget(condition_label)self.weather_layout.addWidget(humidity_label)self.weather_layout.addWidget(wind_label)# 更新AI建議self.update_ai_advice(data)def update_ai_advice(self, data):"""根據天氣更新AI建議"""temp = data["temp_c"]condition = data["condition"]if temp > 30:advice = "天氣炎熱,建議穿著清涼透氣的衣物,避免長時間在戶外暴曬,注意補充水分防止中暑。"color = "#d32f2f"elif temp > 20:advice = "溫度適中,適宜戶外活動,建議穿著輕薄衣物,享受美好的一天。"color = "#1976d2"else:advice = "天氣較涼,建議添加外套,注意保暖以防感冒。"color = "#00796b"if "雨" in condition:advice += " 降水概率高,出行請攜帶雨具。"self.ai_content.setText(advice)self.ai_content.setStyleSheet(f"color: {color}; font-weight: bold;")self.ai_label.setText(f"TianQi AI建議 ({condition} {temp}°C):")def paintEvent(self, event):"""添加漸變背景"""painter = QPainter(self)gradient = QLinearGradient(0, 0, self.width(), self.height())gradient.setColorAt(0, QColor("#e3f2fd"))gradient.setColorAt(1, QColor("#bbdefb"))painter.fillRect(self.rect(), gradient)super().paintEvent(event)if __name__ == "__main__":# 在QApplication初始化后添加app = QApplication(sys.argv)app.setFont(QFont('Microsoft YaHei, Segoe UI Symbol, Noto Color Emoji', 10))  # 指定支持Unicode的字體window = App()window.show()sys.exit(app.exec_())

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/912707.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/912707.shtml
英文地址,請注明出處:http://en.pswp.cn/news/912707.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

PL-SLAM: Real-Time Monocular Visual SLAM with Points and Lines

PL-SLAM 文章目錄 PL-SLAM摘要系統介紹綜述方法綜述LINE-BASED SLAM一、基于線的SLAM二、基于線和點的BA三、全局重定位使用線條初始化地圖實驗結果說明位姿求解三角化LSD 直線檢測算法?? **一、核心原理**?? **二、實現方法**?? **三、應用場景**?? **四、優缺點與優化…

快速手搓一個MCP服務指南(八):FastMCP 代理服務器:構建靈活的 MCP 服務中介層

在分布式系統和微服務架構日益普及的今天,服務間的通信與集成變得至關重要。FastMCP 從 2.0.0 版本引入的代理服務器功能,為 MCP (Model Context Protocol) 生態提供了強大的服務中介能力。本文將深入解析 FastMCP 代理服務器的核心概念、應用場景與實踐…

Ubuntu20下安裝SAMBA服務

1、安裝Samba: 在 Ubuntu 上,打開終端,并運行以下命令以安裝 Samba sudo apt update sudo apt install samba 2、配置共享目錄 修改共享目錄的權限,我的共享目錄是samba_share sudo chmod -R 777 ./samba_share 創建Samba用戶賬號 sud…

Python 數據分析與機器學習入門 (一):環境搭建與核心庫概覽

Python 數據分析與機器學習入門 (一):環境搭建與核心庫概覽 本文摘要 本文是 Python 數據分析與機器學習入門系列的第一篇,專為初學者設計。文章首先闡明了 Python在數據科學領域的優勢,然后手把手指導讀者如何使用 Anaconda 搭建一個無痛、專…

編譯UltraleapTrackingWebSocket

最近要在項目中用到 Leap Motion,無意中發現了一個 Go 語言的 Leap Motion 庫: https://gobot.io/documentation/platforms/leapmotion/ 示例代碼看起來很簡單,但是要實際運行起來還需要一些條件。 在示例代碼中,我們看到它連接…

[ linux-系統 ] 磁盤與文件系統

1.認識磁盤結構 機械鍵盤是計算機中唯一的機械設備,磁盤是外設,容量大,速度慢,價格便宜 物理結構: 磁頭是一面一個,左右擺動,兩個整體移動的,有磁頭停靠點磁頭和盤面不接觸&#x…

Spring AI RAG

目錄 Spring AI 介紹 Spring AI 組件介紹 Spring AI 結構化輸出 Srping AI 多模態 Spring AI 本地Ollama Spring AI 源碼 Spring AI Advisor機制 Spring AI Tool Calling Spring AI MCP Spring AI RAG Spring AI Agent 一、技術架構與核心流程? 檢索增強生成 (RA…

深入Linux開發核心:掌握Vim編輯器與GCCG++編譯工具鏈

文章目錄 一、Vim:終端環境下的編輯藝術1.1 Vim設計哲學:模態編輯的終極實踐1.2 高效導航:超越方向鍵的移動藝術1.3 定制化開發環境:從基礎到專業IDE1.4 調試集成:Vim作為調試前端 二、GCC/G:Linux編譯基石…

阿里云-spring boot接入arms監控

目標:在ecs中啟動一個java應用,且攜帶arms監控 原理:在java應用啟動時,同時啟動一個agent探針,時刻監控java應用變化(如:接口調用、CPU、線程池狀態等) 1.arms接入中心添加java應用…

昆泰芯3D霍爾磁傳感器芯片在汽車零部件中的應用

HUD即抬頭顯示系統(Head-Up Display),HUD 是一種將重要的車輛或飛行等相關信息(如速度、導航指示、警告信息等)投射到駕駛員或操作員前方視野范圍內的透明顯示屏或直接投射到風擋玻璃上的技術。 HUD即抬頭顯示系統(Head-Up Display)&#xff…

new Vue() 的底層工作原理

當你調用 new Vue() 時,Vue.js 會執行一系列復雜的初始化過程。讓我們深入剖析這個看似簡單的操作背后發生的事情: 1. 初始化階段 (1) 內部初始化 function Vue(options) {if (!(this instanceof Vue)) {warn(Vue is a constructor and should be cal…

最簡安裝SUSE15SP7導致大部分命令缺失

我嘞個去~~~明明選擇Enable了ssh,結果也沒給裝。 俺習慣使用NetworkManager管理網絡,沒給裝,用不了nmcli和nmtui。不高興歸不高興,最簡安裝的話,也情有可原。我嘞個去去~~連ping、vi都沒有裝,這也太簡了。…

Vue-14-前端框架Vue之應用基礎嵌套路由和路由傳參

文章目錄 1 嵌套路由1.1 News.vue1.2 Detail.vue1.3 router/index.ts2 路由傳參2.1 query參數2.1.1 News.vue(傳遞參數)2.1.2 Detail.vue(接收參數)2.2 params參數2.2.1 router/index.ts(需要提前占位)2.2.2 News.vue(傳遞參數)2.2.3 Detail.vue(接收參數)2.3 props配置2.3.1 r…

Python網安-ftp服務暴力破解(僅供學習)

目錄 源碼在這里 需要導入的模塊 連接ftp,并設置密碼本和線程 核心代碼 設置線程 源碼在這里 https://github.com/Wist-fully/Attack/tree/cracker 需要導入的模塊 import ftplib from threading import Thread import queue 連接ftp,并設置密碼…

ES6數組的`flat()`和`flatMap()`函數用法

今天給大家分享ES6中兩個超實用的數組函數:flat()和flatMap(),學會它們能讓數組處理變得更輕松! 1. flat()函數 1.1 基本介紹 flat()用于將嵌套數組"拍平",即將多維數組轉換為一維數組。 1.2 語法 const newArray …

upload-labs靶場通關詳解:第15-16關

第十五關 getimagesize函數驗證 一、分析源代碼 function isImage($filename){$types .jpeg|.png|.gif;if(file_exists($filename)){$info getimagesize($filename);$ext image_type_to_extension($info[2]);if(stripos($types,$ext)>0){return $ext;}else{return false…

【Linux】基礎IO流

好的代碼自己會說話,清晰的邏輯與優雅的結構,是程序員與世界對話的方式。 前言 這是我自己學習Linux系統編程的第五篇筆記。后期我會繼續把Linux系統編程筆記開源至博客上。 上一期筆記是關于進程: 【Linux】進程-CSDN博客https://blog.csdn…

【C語言】學習過程教訓與經驗雜談:思想準備、知識回顧(二)

🔥個人主頁:艾莉絲努力練劍 ?專欄傳送門:《C語言》、《數據結構與算法》、C語言刷題12天IO強訓、LeetCode代碼強化刷題 🍉學習方向:C/C方向 ??人生格言:為天地立心,為生民立命,為…

AD8021ARZ-REEL7【ADI】300MHz低噪聲運放放大器,高頻信號處理的性價比之選!

AD8021ARZ-REEL7(ADI)產品解析與推廣文案 1. 產品概述 AD8021ARZ-REEL7 是 Analog Devices Inc.(ADI) 推出的一款 高速、低噪聲運算放大器(Op-Amp),屬于 ADI的高性能放大器系列,專為…

WPF學習筆記(11)數據模板DataTemplate與數據模板選擇器DataTemplateSelector

數據模板DataTemplate與數據模板選擇器DataTemplateSelector 一、DataTemplate1. DataTemplate概述2. DataTemplate詳解 二、DataTemplateSelector1. DataTemplateSelector概述2. DataTemplateSelector詳解 總結 一、DataTemplate 1. DataTemplate概述 DataTemplate 表示數據…