无法从openweathermap获取天气图标

时间:2019-10-05 19:14:15

标签: python api tkinter openweathermap

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

但是,我可以将图标打印为文本,例如其代码类似"3d""3n",但不包含图片。

当我尝试打印图像时,将弹出错误_tkinter.TclError: image "03n" doesn't exist

我的代码在下面。

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)

1 个答案:

答案 0 :(得分:2)

  

问题:从openweathermap获取天气图标

根据评论:

  • 图标的值为“ 03n”。当然,tkinter不知道该如何显示。您必须在openweathermap的API文档中查看如何获取该图标。 – @zvone

  • 请参阅SO:回答set a tkinter app icon with a URL?以获取图标。
    使用f'http://openweathermap.org/img/wn/{icon}.png'作为网址。 – @Stef


enter image description here

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)
  

用法

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()

使用Python测试:3.5