已编写天气判断逻辑,如何用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
相关产品推荐
相关产品推荐

