You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

已编写天气判断逻辑,如何用PIL和url.request加载OpenWeatherMap的PNG?

解决方法

修正条件判断逻辑

你的原代码存在语法错误,比如if condition == "clear" or "clear sky"这种写法会让该条件永远成立(因为字符串"clear sky"本身是真值)。正确写法可以用列表包含判断,更简洁:

if condition in ["clear", "clear sky"]:
    weather_png = "http://openweathermap.org/img/wn/01d@2x.png"
elif condition == "few clouds":
    weather_png = "http://openweathermap.org/img/wn/02d@2x.png"
elif condition == "scattered clouds":
    weather_png = "http://openweathermap.org/img/wn/03d@2x.png"
elif condition in ["broken clouds", "overcast clouds"]:
    weather_png = "http://openweathermap.org/img/wn/04d@2x.png"

打开并显示图片的代码

利用urllib.request获取图片二进制流,再通过PIL的Image类读取并显示:

from PIL import Image
import urllib.request

# 确保weather_png已通过上述逻辑获取到有效URL
with urllib.request.urlopen(weather_png) as img_response:
    weather_image = Image.open(img_response)
    weather_image.show()

说明

  • urlopen直接从目标URL拉取图片的二进制数据,无需先保存到本地文件
  • Image.open()可以直接读取网络返回的二进制流对象
  • show()会调用系统默认的图片查看器展示图片

内容的提问来源于stack exchange,提问作者TAC

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 22:50:36