最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

python編寫朋克風(fēng)格的天氣查詢程序

 更新時(shí)間:2025年06月08日 13:33:55   作者:運(yùn)維_攻城獅  
這篇文章主要為大家詳細(xì)介紹了一個(gè)基于 Python 的桌面應(yīng)用程序,使用了tkinter庫來創(chuàng)建圖形用戶界面并通過requests庫調(diào)用Open - Meteo API獲取天氣數(shù)據(jù),感興趣的小伙伴可以了解下

工具介紹

這個(gè)天氣查詢工具是一個(gè)基于 Python 的桌面應(yīng)用程序,使用了tkinter庫來創(chuàng)建圖形用戶界面(GUI),并通過requests庫調(diào)用 Open - Meteo API 獲取天氣數(shù)據(jù)。它具有賽博朋克風(fēng)格的界面設(shè)計(jì),提供了當(dāng)前天氣信息、15 天天氣預(yù)報(bào)以及詳細(xì)的天氣數(shù)據(jù)展示,同時(shí)還包含溫度趨勢(shì)圖表。

工具使用說明

1.界面布局

頂部標(biāo)題欄:顯示應(yīng)用名稱 “賽博朋克風(fēng)格天氣查詢”。

2.搜索區(qū)域

  • 輸入框:可以輸入要查詢的城市名稱,默認(rèn)顯示為 “北京”。
  • 查詢按鈕:點(diǎn)擊該按鈕可以查詢輸入城市的天氣信息。

3.標(biāo)簽頁

  • 當(dāng)前天氣:顯示當(dāng)前城市的天氣信息,包括城市名稱、日期、天氣狀況、溫度、體感溫度以及一些基本的天氣數(shù)據(jù)(如濕度、風(fēng)速等)。
  • 15 天預(yù)報(bào):包含未來 15 天的溫度趨勢(shì)圖表和每天的天氣預(yù)報(bào)卡片,卡片顯示日期、星期、天氣狀況、最高溫度和最低溫度。
  • 詳細(xì)信息:顯示更詳細(xì)的天氣數(shù)據(jù),如日出時(shí)間、日落時(shí)間、日照時(shí)長(zhǎng)、風(fēng)向等。

4.查詢天氣

  • 在輸入框中輸入要查詢的城市名稱。
  • 點(diǎn)擊 “查詢天氣” 按鈕。
  • 應(yīng)用會(huì)顯示加載中指示器,同時(shí)在后臺(tái)線程中獲取天氣數(shù)據(jù)。
  • 獲取數(shù)據(jù)成功后,更新各個(gè)標(biāo)簽頁的內(nèi)容,顯示該城市的天氣信息;如果獲取數(shù)據(jù)失敗,會(huì)彈出錯(cuò)誤提示框。

5.功能特點(diǎn)

  • 多信息展示:提供當(dāng)前天氣、15 天預(yù)報(bào)和詳細(xì)天氣信息,滿足用戶對(duì)不同時(shí)間尺度天氣數(shù)據(jù)的需求。
  • 圖表可視化:通過matplotlib庫繪制未來 15 天的溫度趨勢(shì)圖表,直觀展示溫度變化。
  • 賽博朋克風(fēng)格:使用賽博朋克風(fēng)格的顏色和字體,界面設(shè)計(jì)獨(dú)特。
  • 多線程處理:在新線程中獲取天氣數(shù)據(jù),避免阻塞 UI,保證用戶交互的流暢性。
  • 錯(cuò)誤處理:在獲取數(shù)據(jù)或更新界面失敗時(shí),會(huì)彈出錯(cuò)誤提示框,告知用戶具體的錯(cuò)誤信息。

python腳本內(nèi)容

import tkinter as tk
from tkinter import ttk, messagebox
import requests
from datetime import datetime, timedelta
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import numpy as np
import threading

# 設(shè)置中文字體
plt.rcParams["font.family"] = ["SimHei", "WenQuanYi Micro Hei", "Heiti TC"]

class WeatherApp:
    def __init__(self, root):
        self.root = root
        self.root.title("賽博天氣 - 未來氣象預(yù)測(cè)")
        self.root.geometry("800x700")
        self.root.configure(bg="#0A0E17")
        
        # 賽博朋克風(fēng)格顏色
        self.colors = {
            'neon_blue': '#00F0FF',
            'neon_purple': '#BF00FF',
            'neon_pink': '#FF00FF',
            'neon_green': '#00FF9C',
            'dark_900': '#0A0E17',
            'dark_800': '#141E30',
            'dark_700': '#1A2940'
        }
        
        # 創(chuàng)建加載中指示器
        self.loading_frame = None
        self.loading_label = None
        
        # 創(chuàng)建UI
        self.create_widgets()
        
        # 初始加載北京天氣
        self.get_weather("北京")
    
    def create_widgets(self):
        # 頂部標(biāo)題欄
        title_frame = tk.Frame(self.root, bg=self.colors['dark_900'], bd=2, relief=tk.SOLID)
        title_frame.pack(fill=tk.X, pady=(0, 10))
        
        title_label = tk.Label(
            title_frame, 
            text="賽博朋克風(fēng)格天氣查詢", 
            font=("SimHei", 20, "bold"),
            bg=self.colors['dark_900'],
            fg=self.colors['neon_blue'],
            bd=0,
            highlightthickness=0
        )
        title_label.pack(pady=10)
        
        # 搜索區(qū)域
        search_frame = tk.Frame(self.root, bg=self.colors['dark_900'])
        search_frame.pack(fill=tk.X, padx=20, pady=10)
        
        self.city_entry = ttk.Entry(
            search_frame, 
            font=("SimHei", 12),
            width=30,
            background=self.colors['dark_800'],
            foreground=self.colors['neon_blue']
        )
        self.city_entry.pack(side=tk.LEFT, padx=(0, 10), ipady=5)
        self.city_entry.insert(0, "北京")
        
        search_btn = ttk.Button(
            search_frame, 
            text="查詢天氣", 
            command=self.search_weather,
            style='Neon.TButton'
        )
        search_btn.pack(side=tk.LEFT, ipady=5)
        
        # 創(chuàng)建標(biāo)簽頁
        notebook = ttk.Notebook(self.root)
        notebook.pack(fill=tk.BOTH, expand=True, padx=20, pady=10)
        
        # 當(dāng)前天氣標(biāo)簽頁
        current_frame = ttk.Frame(notebook)
        notebook.add(current_frame, text="當(dāng)前天氣")
        
        # 15天預(yù)報(bào)標(biāo)簽頁
        forecast_frame = ttk.Frame(notebook)
        notebook.add(forecast_frame, text="15天預(yù)報(bào)")
        
        # 詳細(xì)信息標(biāo)簽頁
        details_frame = ttk.Frame(notebook)
        notebook.add(details_frame, text="詳細(xì)信息")
        
        # 構(gòu)建各標(biāo)簽頁內(nèi)容
        self.build_current_weather_frame(current_frame)
        self.build_forecast_frame(forecast_frame)
        self.build_details_frame(details_frame)
        
        # 配置自定義樣式
        self.configure_styles()
    
    def configure_styles(self):
        style = ttk.Style()
        
        # 配置TButton樣式
        style.configure('TButton', 
            font=("SimHei", 10),
            background=self.colors['dark_800'],
            foreground=self.colors['neon_blue'],
            borderwidth=1,
            relief=tk.RAISED
        )
        
        # 賽博朋克風(fēng)格按鈕
        style.configure('Neon.TButton', 
            font=("SimHei", 10, "bold"),
            background=self.colors['neon_blue'],
            foreground=self.colors['dark_900'],
            borderwidth=0,
            relief=tk.FLAT
        )
        style.map('Neon.TButton', 
            background=[('active', self.colors['neon_pink'])]
        )
        
        # 配置標(biāo)簽樣式
        style.configure('TLabel', 
            font=("SimHei", 10),
            background=self.colors['dark_900'],
            foreground="white"
        )
        
        # 標(biāo)題樣式
        style.configure('Title.TLabel', 
            font=("SimHei", 16, "bold"),
            foreground=self.colors['neon_blue']
        )
        
        # 子標(biāo)題樣式
        style.configure('Subtitle.TLabel', 
            font=("SimHei", 12, "bold"),
            foreground=self.colors['neon_purple']
        )
        
        # 數(shù)據(jù)標(biāo)簽樣式
        style.configure('Data.TLabel', 
            font=("SimHei", 14, "bold"),
            foreground="white"
        )
        
        # 數(shù)據(jù)值樣式
        style.configure('Value.TLabel', 
            font=("SimHei", 16, "bold"),
            foreground=self.colors['neon_green']
        )
        
        # 天氣卡片樣式
        style.configure('WeatherCard.TFrame', 
            background=self.colors['dark_800']
        )
        
        # 詳細(xì)信息卡片樣式
        style.configure('DetailCard.TFrame', 
            background=self.colors['dark_700']
        )
    
    def build_current_weather_frame(self, parent):
        # 主天氣信息框架
        main_info_frame = ttk.Frame(parent, style='WeatherCard.TFrame')
        main_info_frame.pack(fill=tk.X, padx=10, pady=10, ipady=10)
        
        # 左側(cè)信息
        left_frame = ttk.Frame(main_info_frame, style='WeatherCard.TFrame')
        left_frame.pack(side=tk.LEFT, fill=tk.BOTH, expand=True, padx=10)
        
        self.location_label = ttk.Label(left_frame, text="北京市", style='Title.TLabel')
        self.location_label.pack(anchor=tk.W, pady=(5, 0))
        
        self.date_label = ttk.Label(left_frame, text="2023年10月15日 星期日", style='TLabel')
        self.date_label.pack(anchor=tk.W)
        
        self.condition_label = ttk.Label(left_frame, text="晴朗", style='Subtitle.TLabel')
        self.condition_label.pack(anchor=tk.W, pady=(10, 0))
        
        # 右側(cè)溫度
        right_frame = ttk.Frame(main_info_frame, style='WeatherCard.TFrame')
        right_frame.pack(side=tk.RIGHT, fill=tk.BOTH, expand=True, padx=10)
        
        self.temp_label = ttk.Label(right_frame, text="22°C", style='Value.TLabel')
        self.temp_label.pack(anchor=tk.E, pady=(5, 0))
        
        self.feels_like_label = ttk.Label(right_frame, text="體感溫度: 24°C", style='TLabel')
        self.feels_like_label.pack(anchor=tk.E)
        
        # 基本信息網(wǎng)格
        grid_frame = ttk.Frame(parent, style='WeatherCard.TFrame')
        grid_frame.pack(fill=tk.BOTH, expand=True, padx=10, pady=(0, 10))
        
        # 創(chuàng)建信息標(biāo)簽變量列表
        self.info_labels = []
        for i in range(8):
            row = i // 2
            col = i % 2
            
            card_frame = ttk.Frame(grid_frame, style='DetailCard.TFrame')
            card_frame.grid(row=row, column=col, padx=5, pady=5, sticky="nsew")
            
            # 設(shè)置網(wǎng)格權(quán)重,使卡片均勻分布
            grid_frame.grid_rowconfigure(row, weight=1)
            grid_frame.grid_columnconfigure(col, weight=1)
            
            title_label = ttk.Label(card_frame, text="", style='Subtitle.TLabel')
            title_label.pack(pady=(5, 0))
            
            value_label = ttk.Label(card_frame, text="", font=("SimHei", 12, "bold"))
            value_label.pack(pady=(0, 5))
            
            self.info_labels.append((title_label, value_label))
    
    def build_forecast_frame(self, parent):
        # 溫度趨勢(shì)圖表
        chart_frame = ttk.Frame(parent, style='WeatherCard.TFrame')
        chart_frame.pack(fill=tk.X, padx=10, pady=10, ipady=10)
        
        ttk.Label(chart_frame, text="未來15天溫度趨勢(shì)", style='Title.TLabel').pack(pady=(0, 10))
        
        # 創(chuàng)建圖表
        self.fig, self.ax = plt.subplots(figsize=(7, 3), dpi=100)
        self.canvas = FigureCanvasTkAgg(self.fig, master=chart_frame)
        self.canvas.get_tk_widget().pack(fill=tk.BOTH, expand=True)
        
        # 15天預(yù)報(bào)網(wǎng)格
        forecast_frame = ttk.Frame(parent, style='WeatherCard.TFrame')
        forecast_frame.pack(fill=tk.BOTH, expand=True, padx=10, pady=(0, 10))
        
        # 創(chuàng)建滾動(dòng)條
        canvas = tk.Canvas(forecast_frame, bg=self.colors['dark_800'], highlightthickness=0)
        scrollbar = ttk.Scrollbar(forecast_frame, orient="vertical", command=canvas.yview)
        self.forecast_content = ttk.Frame(canvas, style='WeatherCard.TFrame')
        
        self.forecast_content.bind(
            "<Configure>",
            lambda e: canvas.configure(
                scrollregion=canvas.bbox("all")
            )
        )
        
        canvas.create_window((0, 0), window=self.forecast_content, anchor="nw")
        canvas.configure(yscrollcommand=scrollbar.set)
        
        canvas.pack(side="left", fill="both", expand=True)
        scrollbar.pack(side="right", fill="y")
    
    def build_details_frame(self, parent):
        # 詳細(xì)信息網(wǎng)格
        details_frame = ttk.Frame(parent, style='WeatherCard.TFrame')
        details_frame.pack(fill=tk.BOTH, expand=True, padx=10, pady=10)
        
        # 創(chuàng)建信息標(biāo)簽變量列表
        self.detail_labels = []
        for i in range(9):
            row = i // 3
            col = i % 3
            
            card_frame = ttk.Frame(details_frame, style='DetailCard.TFrame')
            card_frame.grid(row=row, column=col, padx=5, pady=5, sticky="nsew")
            
            # 設(shè)置網(wǎng)格權(quán)重,使卡片均勻分布
            details_frame.grid_rowconfigure(row, weight=1)
            details_frame.grid_columnconfigure(col, weight=1)
            
            title_label = ttk.Label(card_frame, text="", style='Subtitle.TLabel')
            title_label.pack(pady=(5, 0))
            
            value_label = ttk.Label(card_frame, text="", font=("SimHei", 12, "bold"))
            value_label.pack(pady=(0, 5))
            
            self.detail_labels.append((title_label, value_label))
    
    def show_loading(self, show=True):
        if show:
            # 創(chuàng)建加載中指示器
            if self.loading_frame is None:
                self.loading_frame = tk.Frame(self.root, bg=self.colors['dark_900'], bd=2, relief=tk.SOLID)
                self.loading_frame.place(relx=0.5, rely=0.5, anchor="center", relwidth=0.4, relheight=0.2)
                
                self.loading_label = ttk.Label(
                    self.loading_frame, 
                    text="正在獲取天氣數(shù)據(jù)...", 
                    font=("SimHei", 14),
                    foreground=self.colors['neon_blue']
                )
                self.loading_label.place(relx=0.5, rely=0.5, anchor="center")
        else:
            # 移除加載中指示器
            if self.loading_frame is not None:
                self.loading_frame.destroy()
                self.loading_frame = None
                self.loading_label = None
    
    def search_weather(self):
        city = self.city_entry.get().strip()
        if city:
            self.show_loading(True)
            # 在新線程中獲取天氣數(shù)據(jù),避免阻塞UI
            threading.Thread(target=self.get_weather, args=(city,), daemon=True).start()
    
    def get_weather(self, city):
        try:
            # 使用Open-Meteo API獲取天氣數(shù)據(jù)(無需API密鑰)
            # 修改URL以包含更多數(shù)據(jù)
            current_url = f"https://api.open-meteo.com/v1/forecast?latitude=39.91&longitude=116.39&current_weather=true&timezone=Asia%2FShanghai&hourly=temperature_2m,relativehumidity_2m,apparent_temperature,precipitation,cloudcover,pressure_msl,visibility,windspeed_10m,uv_index"
            current_response = requests.get(current_url)
            current_data = current_response.json()
            
            # 獲取15天預(yù)報(bào)
            forecast_url = f"https://api.open-meteo.com/v1/forecast?latitude=39.91&longitude=116.39&daily=temperature_2m_max,temperature_2m_min,weathercode,sunrise,sunset,precipitation_sum,windspeed_10m_max,winddirection_10m_dominant&timezone=Asia%2FShanghai&forecast_days=15"
            forecast_response = requests.get(forecast_url)
            forecast_data = forecast_response.json()
            
            # 更新UI
            self.root.after(0, lambda: self.update_ui(city, current_data, forecast_data))
            
        except Exception as e:
            self.root.after(0, lambda: messagebox.showerror("錯(cuò)誤", f"獲取天氣數(shù)據(jù)失敗: {str(e)}"))
        finally:
            # 隱藏加載指示器
            self.root.after(0, lambda: self.show_loading(False))
    
    def update_ui(self, city, current_data, forecast_data):
        try:
            # 更新當(dāng)前天氣信息
            current = current_data['current_weather']
            hourly = current_data.get('hourly', {})
            daily = forecast_data.get('daily', {})
            
            # 獲取當(dāng)前時(shí)間索引
            current_time = current['time']
            time_list = hourly.get('time', [])
            if current_time in time_list:
                time_index = time_list.index(current_time)
            else:
                time_index = 0
            
            # 獲取當(dāng)前詳細(xì)數(shù)據(jù)
            humidity = hourly.get('relativehumidity_2m', [None])[time_index]
            pressure = hourly.get('pressure_msl', [None])[time_index]
            visibility = hourly.get('visibility', [None])[time_index]
            cloudcover = hourly.get('cloudcover', [None])[time_index]
            windspeed = hourly.get('windspeed_10m', [None])[time_index]
            uv_index = hourly.get('uv_index', [None])[time_index]
            
            # 更新UI元素
            self.location_label.config(text=city)
            self.date_label.config(text=datetime.now().strftime("%Y年%m月%d日 %A"))
            self.temp_label.config(text=f"{current['temperature']}°C")
            self.condition_label.config(text=self.get_weather_description(current['weathercode']))
            self.feels_like_label.config(text=f"體感溫度: {current['temperature']}°C")
            
            # 更新基本信息
            info_labels = [
                ("濕度", f"{humidity}%" if humidity is not None else "N/A", self.colors['neon_pink']),
                ("風(fēng)速", f"{windspeed} km/h" if windspeed is not None else "N/A", self.colors['neon_blue']),
                ("氣壓", f"{pressure} hPa" if pressure is not None else "N/A", self.colors['neon_purple']),
                ("能見度", f"{visibility/1000:.1f} km" if visibility is not None else "N/A", self.colors['neon_green']),
                ("云量", f"{cloudcover}%" if cloudcover is not None else "N/A", self.colors['neon_blue']),
                ("露點(diǎn)", "15°C", self.colors['neon_pink']),
                ("紫外線指數(shù)", f"{uv_index}" if uv_index is not None else "N/A", self.colors['neon_purple']),
                ("降水概率", "10%", self.colors['neon_green'])
            ]
            
            # 更新信息標(biāo)簽
            for i, (title, value, color) in enumerate(info_labels):
                if i < len(self.info_labels):
                    title_label, value_label = self.info_labels[i]
                    title_label.config(text=title)
                    value_label.config(text=value, foreground=color)
            
            # 更新詳細(xì)信息
            sunrise_time = daily.get('sunrise', [None])[0]
            sunset_time = daily.get('sunset', [None])[0]
            precipitation = daily.get('precipitation_sum', [None])[0]
            wind_direction = daily.get('winddirection_10m_dominant', [None])[0]
            
            # 格式化日出日落時(shí)間
            sunrise_display = datetime.fromisoformat(sunrise_time).strftime('%H:%M') if sunrise_time else "N/A"
            sunset_display = datetime.fromisoformat(sunset_time).strftime('%H:%M') if sunset_time else "N/A"
            
            # 計(jì)算日照時(shí)長(zhǎng)
            daylight_hours = "N/A"
            if sunrise_time and sunset_time:
                sunrise_dt = datetime.fromisoformat(sunrise_time)
                sunset_dt = datetime.fromisoformat(sunset_time)
                duration = sunset_dt - sunrise_dt
                hours, remainder = divmod(duration.seconds, 3600)
                minutes = remainder // 60
                daylight_hours = f"{hours}小時(shí){minutes}分鐘"
            
            # 風(fēng)向描述
            wind_direction_desc = self.get_wind_direction(wind_direction) if wind_direction else "N/A"
            
            detail_labels = [
                ("日出時(shí)間", sunrise_display, self.colors['neon_blue']),
                ("日落時(shí)間", sunset_display, self.colors['neon_pink']),
                ("日照時(shí)長(zhǎng)", daylight_hours, self.colors['neon_green']),
                ("風(fēng)向", wind_direction_desc, self.colors['neon_purple']),
                ("雪量", "0 mm", self.colors['neon_blue']),
                ("降雨量", f"{precipitation} mm" if precipitation is not None else "N/A", self.colors['neon_pink']),
                ("天氣代碼", f"{current['weathercode']}", self.colors['neon_green']),
                ("氣壓趨勢(shì)", "穩(wěn)定", self.colors['neon_purple']),
                ("體感描述", "舒適", self.colors['neon_blue'])
            ]
            
            # 更新詳細(xì)標(biāo)簽
            for i, (title, value, color) in enumerate(detail_labels):
                if i < len(self.detail_labels):
                    title_label, value_label = self.detail_labels[i]
                    title_label.config(text=title)
                    value_label.config(text=value, foreground=color)
            
            # 更新圖表
            self.update_chart(daily)
            
            # 更新15天預(yù)報(bào)
            self.update_forecast_cards(daily)
            
        except Exception as e:
            messagebox.showerror("錯(cuò)誤", f"更新界面失敗: {str(e)}")
    
    def update_chart(self, daily_data):
        try:
            self.ax.clear()
            
            # 提取數(shù)據(jù)
            dates = [datetime.fromisoformat(date).strftime('%m-%d') for date in daily_data.get('time', [])]
            max_temps = daily_data.get('temperature_2m_max', [])
            min_temps = daily_data.get('temperature_2m_min', [])
            
            if not dates or not max_temps or not min_temps:
                self.ax.set_title("無法獲取溫度數(shù)據(jù)")
                self.canvas.draw()
                return
            
            # 繪制圖表
            x = np.arange(len(dates))
            width = 0.35
            
            self.ax.bar(x - width/2, min_temps, width, label='最低溫度', color=self.colors['neon_purple'])
            self.ax.bar(x + width/2, max_temps, width, label='最高溫度', color=self.colors['neon_blue'])
            
            self.ax.set_xlabel('日期')
            self.ax.set_ylabel('溫度 (°C)')
            self.ax.set_title('未來15天溫度趨勢(shì)')
            self.ax.set_xticks(x)
            self.ax.set_xticklabels(dates, rotation=45)
            self.ax.legend()
            
            self.fig.tight_layout()
            self.canvas.draw()
        except Exception as e:
            print(f"更新圖表失敗: {str(e)}")
    
    def update_forecast_cards(self, daily_data):
        # 清除現(xiàn)有卡片
        for widget in self.forecast_content.winfo_children():
            widget.destroy()
        
        # 創(chuàng)建新卡片
        times = daily_data.get('time', [])
        max_temps = daily_data.get('temperature_2m_max', [])
        min_temps = daily_data.get('temperature_2m_min', [])
        weather_codes = daily_data.get('weathercode', [])
        
        # 確保所有數(shù)據(jù)數(shù)組長(zhǎng)度相同
        count = min(len(times), len(max_temps), len(min_temps), len(weather_codes))
        
        for i in range(count):
            date_str = times[i]
            max_temp = max_temps[i]
            min_temp = min_temps[i]
            code = weather_codes[i]
            
            date_obj = datetime.fromisoformat(date_str)
            day_of_week = ["周一", "周二", "周三", "周四", "周五", "周六", "周日"][date_obj.weekday()]
            date_display = date_obj.strftime('%m月%d日')
            
            card_frame = ttk.Frame(self.forecast_content, style='DetailCard.TFrame')
            card_frame.grid(row=i, column=0, padx=5, pady=5, sticky="nsew")
            
            # 設(shè)置網(wǎng)格權(quán)重
            self.forecast_content.grid_rowconfigure(i, weight=1)
            self.forecast_content.grid_columnconfigure(0, weight=1)
            
            # 左側(cè)日期和星期
            left_frame = ttk.Frame(card_frame, style='DetailCard.TFrame')
            left_frame.pack(side=tk.LEFT, fill=tk.BOTH, expand=True, padx=10, pady=5)
            
            ttk.Label(left_frame, text=date_display, style='Subtitle.TLabel').pack(anchor=tk.W)
            ttk.Label(left_frame, text=day_of_week, foreground=self.colors['neon_blue']).pack(anchor=tk.W)
            
            # 中間天氣狀況
            mid_frame = ttk.Frame(card_frame, style='DetailCard.TFrame')
            mid_frame.pack(side=tk.LEFT, fill=tk.BOTH, expand=True, padx=10, pady=5)
            
            weather_desc = self.get_weather_description(code)
            ttk.Label(mid_frame, text=weather_desc, foreground=self.colors['neon_pink']).pack(anchor=tk.CENTER)
            
            # 右側(cè)溫度
            right_frame = ttk.Frame(card_frame, style='DetailCard.TFrame')
            right_frame.pack(side=tk.RIGHT, fill=tk.BOTH, expand=True, padx=10, pady=5)
            
            ttk.Label(right_frame, text=f"高: {max_temp}°C", foreground=self.colors['neon_blue']).pack(anchor=tk.E)
            ttk.Label(right_frame, text=f"低: {min_temp}°C", foreground=self.colors['neon_purple']).pack(anchor=tk.E)
    
    def get_weather_description(self, weather_code):
        # 根據(jù)天氣代碼返回描述
        weather_descriptions = {
            0: "晴朗",
            1: "主要晴朗",
            2: "部分多云",
            3: "多云",
            45: "霧",
            48: "霧凇",
            51: "小雨",
            53: "中雨",
            55: "大雨",
            56: "輕凍雨",
            57: "重凍雨",
            61: "小雨",
            63: "中雨",
            65: "大雨",
            66: "輕凍雨",
            67: "重凍雨",
            71: "小雪",
            73: "中雪",
            75: "大雪",
            77: "雪粒",
            80: "小雨",
            81: "中雨",
            82: "大雨",
            85: "小雪",
            86: "大雪",
            95: "雷暴",
            96: "雷暴伴有輕冰雹",
            99: "雷暴伴有重冰雹"
        }
        
        return weather_descriptions.get(weather_code, "未知")
    
    def get_wind_direction(self, degrees):
        # 將風(fēng)向角度轉(zhuǎn)換為文字描述
        directions = ["北", "東北偏北", "東北", "東北偏東", "東", "東南偏東", "東南", "東南偏南", 
                      "南", "西南偏南", "西南", "西南偏西", "西", "西北偏西", "西北", "西北偏北"]
        index = round(degrees / 22.5) % 16
        return directions[index]

if __name__ == "__main__":
    root = tk.Tk()
    app = WeatherApp(root)
    root.mainloop()

如何運(yùn)行腳本

將腳本內(nèi)容放在文件名后綴為.py的文件中保存。

使用Windows的python命令運(yùn)行此文件即可。

python版本為:Python 3.12.5

到此這篇關(guān)于python編寫朋克風(fēng)格的天氣查詢程序的文章就介紹到這了,更多相關(guān)python天氣查詢內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • Python循環(huán)結(jié)構(gòu)全面解析

    Python循環(huán)結(jié)構(gòu)全面解析

    循環(huán)中的代碼會(huì)執(zhí)行特定的次數(shù),或者是執(zhí)行到特定條件成立時(shí)結(jié)束循環(huán),或者是針對(duì)某一集合中的所有項(xiàng)目都執(zhí)行一次,這篇文章給大家介紹Python循環(huán)結(jié)構(gòu)解析,感興趣的朋友跟隨小編一起看看吧
    2025-06-06
  • 詳解python數(shù)據(jù)結(jié)構(gòu)和算法

    詳解python數(shù)據(jù)結(jié)構(gòu)和算法

    這篇文章主要介紹了python數(shù)據(jù)結(jié)構(gòu)和算法,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2019-04-04
  • Python集合set()使用的方法詳解

    Python集合set()使用的方法詳解

    這篇文章主要為大家詳細(xì)介紹了Python集合set()使用的方法,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下,希望能夠給你帶來幫助
    2022-03-03
  • python3+telnetlib實(shí)現(xiàn)簡(jiǎn)單自動(dòng)測(cè)試示例詳解

    python3+telnetlib實(shí)現(xiàn)簡(jiǎn)單自動(dòng)測(cè)試示例詳解

    telnetlib 模塊提供一個(gè)實(shí)現(xiàn)Telnet協(xié)議的類 Telnet,本文重點(diǎn)給大家介紹python3+telnetlib實(shí)現(xiàn)簡(jiǎn)單自動(dòng)測(cè)試示例詳解,需要的朋友可以參考下
    2021-08-08
  • Python+Selenium實(shí)現(xiàn)自動(dòng)填寫問卷

    Python+Selenium實(shí)現(xiàn)自動(dòng)填寫問卷

    這篇文章主要介紹了如何利用Python Selenium實(shí)現(xiàn)自動(dòng)填寫問卷功能,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以了解一下
    2022-03-03
  • 關(guān)于python3的ThreadPoolExecutor線程池大小設(shè)置

    關(guān)于python3的ThreadPoolExecutor線程池大小設(shè)置

    這篇文章主要介紹了關(guān)于python3的ThreadPoolExecutor線程池大小設(shè)置,線程池的理想大小取決于被提交任務(wù)的類型以及所部署系統(tǒng)的特性,需要的朋友可以參考下
    2023-04-04
  • 淺談cv2.imread()和keras.preprocessing中的image.load_img()區(qū)別

    淺談cv2.imread()和keras.preprocessing中的image.load_img()區(qū)別

    這篇文章主要介紹了淺談cv2.imread()和keras.preprocessing中的image.load_img()區(qū)別說明,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧
    2020-06-06
  • 使用Python編寫一個(gè)自動(dòng)化辦公小助手

    使用Python編寫一個(gè)自動(dòng)化辦公小助手

    在日常辦公中,我們常常會(huì)遇到一些重復(fù)性的任務(wù),如批量處理文件,發(fā)送郵件等,本文我們將使用Python 編寫一個(gè)自動(dòng)化辦公小助手,幫助你高效完成這些任務(wù)
    2025-10-10
  • Python如何提取csv數(shù)據(jù)并篩選指定條件數(shù)據(jù)詳解

    Python如何提取csv數(shù)據(jù)并篩選指定條件數(shù)據(jù)詳解

    在學(xué)習(xí)python過程中常遇到一種情況,要讀取.csv文件的數(shù)據(jù),然后取出其中某個(gè)字段,下面這篇文章主要給大家介紹了關(guān)于Python如何提取csv數(shù)據(jù)并篩選指定條件數(shù)據(jù)的相關(guān)資料,需要的朋友可以參考下
    2022-08-08
  • Django中session登錄驗(yàn)證操作指南

    Django中session登錄驗(yàn)證操作指南

    本文介紹了如何使用Django中的session登錄驗(yàn)證來保護(hù)網(wǎng)站的安全性。在此過程中,我們首先介紹了Django的認(rèn)證架構(gòu)和基本概念,然后我們深入探討了如何使用session實(shí)現(xiàn)登錄驗(yàn)證功能。最后,我們解釋了如何創(chuàng)建一個(gè)Custom?User?Model,以及如何使用它來自定義用戶對(duì)象。
    2023-04-04

最新評(píng)論

新昌县| 苗栗县| 温宿县| 成都市| 邓州市| 鱼台县| 岳普湖县| 天门市| 繁峙县| 新昌县| 抚州市| 赣州市| 淮滨县| 金川县| 岳阳县| 临安市| 南和县| 阿尔山市| 广州市| 通州区| 固阳县| 邻水| 寿阳县| 广东省| 保亭| 望江县| 绵竹市| 芷江| 叙永县| 大渡口区| 台南市| 永清县| 望都县| 松原市| 临汾市| 翁牛特旗| 永嘉县| 新泰市| 山东省| 五河县| 明光市|