无法从 openweathermap 获取天气图标 [英] Can't fetch weather icons from openweathermap

查看:44
本文介绍了无法从 openweathermap 获取天气图标的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试从 openweathermap api 为 python 应用程序获取天气图标,但由于某种原因我无法这样做.

但是,我可以将图标打印为文本,例如它的代码像 "3d""3n" 但不是图像.

当我尝试打印图像时,会弹出错误_tkinter.TclError: image "03n" does not exist.

我的代码如下.

导入请求从 tkinter 导入 *根 = Tk()root.geometry("250x250+0+0")root.configure(bg='black')url = 'http://api.openweathermap.org/data/2.5/weather?appid=c73d9cdb31fd6a386bee66158b116cd0&q=karachi&units=metric'json = requests.get(url).json()温度 = json['main']['temp']icon = json['天气'][0]['icon']#icon1 = 'http://openweathermap.org/img/wn/10d@2x.png'#打印(图标)root.lab1 = 标签(根,图像=图标)root.lab1.pack(side=TOP)root.lab= Label(text=(root,'{} deg celcius'.format(temperature)),font=("Helvetica 15"), bg='black', fg='white')root.lab.pack(side=LEFT)

解决方案

问题:从 openweathermap 获取天气图标

根据评论:

  • 图标的值为03n".当然,tkinter 不知道如何证明这一点.您必须在 openweathermap 的 API 文档中查看如何获取该图标.– @zvone

  • 请参阅 SO:答案

    导入 tkinter 作为 tk导入请求,base64类 OpenWeatherMap:APPID = 'c73d9cdb31fd6a386bee66158b116cd0'def __init__(self):self.url = "http://api.openweathermap.org/data/2.5/weather?appid={appid}&q={city}&units=metric"self.json = {}def get_city(self, city):url = self.url.format(appid=OpenWeatherMap.APPID, city=city)self.json = requests.get(url).json()返回 self.jsondef get(self, key):返回 self.json['main'][key]def get_icon_data(self):icon_id = self.json['天气'][0]['icon']url = 'http://openweathermap.org/img/wn/{icon}.png'.format(icon=icon_id)响应 = requests.get(url, stream=True)返回 base64.encodebytes(response.raw.read())类OWIconLabel(tk.Label):def __init__(self, parent, **kwargs):Weather_icon = kwargs.pop('weather_icon', None)如果weather_icon 不是None:self.photo = tk.PhotoImage(data=weather_icon)kwargs['image'] = self.photosuper().__init__(parent, **kwargs)

    <块引用>

    用法:

    类应用程序(tk.Tk):def __init__(self):super().__init__()self.geometry("220x120+0+0")self.configure(bg='black')owm = OpenWeatherMap()owm.get_city('卡拉奇')温度 = owm.get('temp')temp_icon = OWIconLabel(self,weather_icon=owm.get_icon_data())temp_icon.grid(row=0, column=0)self.temp = tk.Label(self,text='{} deg celcius'.format(温度),font=("Helvetica", 15), bg='black', fg='white')self.temp.grid(row=1, column=0)如果 __name__ == '__main__':应用程序().主循环()

    使用 Python 测试:3.5

    I have been trying to fetch weather icons from openweathermap api for a python application, but for some reason I am not able to do so.

    I am however, able to print the icon as text for e.g. its code like "3d" or "3n" but not the image.

    When I try to print the image, the error _tkinter.TclError: image "03n" doesn't exist pops up.

    My code is below.

    import requests
    from tkinter import *
    
    root = Tk()
    root.geometry("250x250+0+0")
    root.configure(bg='black')
    url = 'http://api.openweathermap.org/data/2.5/weather?appid=c73d9cdb31fd6a386bee66158b116cd0&q=karachi&units=metric'
    
    json = requests.get(url).json()
    temperature = json['main']['temp']
    icon = json['weather'][0]['icon']
    #icon1 = 'http://openweathermap.org/img/wn/10d@2x.png'
    #print(icon)
    root.lab1 = Label(root,image=icon)
    root.lab1.pack(side=TOP)
    root.lab= Label(text=(root,'{} deg celcius'.format(temperature)),font=("Helvetica 15"), bg='black', fg='white')
    root.lab.pack(side=LEFT)
    

    解决方案

    Question: fetch weather icons from openweathermap

    According to the comments:

    • The value of icon is "03n". Of course tkinter does not know how to show that. You have to see in openweathermap's API docs how to fetch that icon. – @zvone

    • see SO:Answer set a tkinter app icon with a URL? to get the icon.
      use f'http://openweathermap.org/img/wn/{icon}.png' as url. – @Stef


    import tkinter as tk
    import requests, base64
    
    class OpenWeatherMap:
        APPID = 'c73d9cdb31fd6a386bee66158b116cd0'
    
        def __init__(self):
            self.url = "http://api.openweathermap.org/data/2.5/weather?appid={appid}&q={city}&units=metric"
            self.json = {}
    
        def get_city(self, city):
            url = self.url.format(appid=OpenWeatherMap.APPID, city=city)
            self.json = requests.get(url).json()
            return self.json
    
        def get(self, key):
            return self.json['main'][key]
    
        def get_icon_data(self):
            icon_id = self.json['weather'][0]['icon']
            url = 'http://openweathermap.org/img/wn/{icon}.png'.format(icon=icon_id)
            response = requests.get(url, stream=True)
            return base64.encodebytes(response.raw.read())
    
    
    class OWIconLabel(tk.Label):
        def __init__(self, parent, **kwargs):
            weather_icon = kwargs.pop('weather_icon', None)
            if weather_icon is not None:
                self.photo = tk.PhotoImage(data=weather_icon)
                kwargs['image'] = self.photo
    
            super().__init__(parent, **kwargs)
    

    Usage:

    class App(tk.Tk):
        def __init__(self):
            super().__init__()
            self.geometry("220x120+0+0")
            self.configure(bg='black')
    
            owm = OpenWeatherMap()
            owm.get_city('karachi')
    
            temperature = owm.get('temp')
    
            temp_icon = OWIconLabel(self, weather_icon=owm.get_icon_data())
            temp_icon.grid(row=0, column=0)
    
            self.temp = tk.Label(self,
                                 text='{} deg celcius'.format(temperature),
                                 font=("Helvetica", 15), bg='black', fg='white')
            self.temp.grid(row=1, column=0)
    
    
    if __name__ == '__main__':
        App().mainloop()
    

    Tested with Python: 3.5

    这篇关于无法从 openweathermap 获取天气图标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆