(Python) 如何从weatherapi.com获取天气图标?

问题描述 投票:0回答:1

我正在尝试使用 Python 和 Tkinter 制作一个天气应用程序。我正在使用来自weatherapi.com 的天气API。除了图标之外,我几乎拥有所有内容,我不知道如何从 .json 文件中获取图标 url,并在不同城市或地点搜索时更新图标。

这是 json 文件的图像,其中当前条件图标为:

这是view.py中的createFrameInfo代码:

#the information of the current condition the text that says "image" is a place holder for the actual icon
def _createFrameInfo(self):
        self.frameInfo = Frame(self.mainframe)
        
        labelTemp = Label(self.frameInfo, textvariable=self.varTemp)
        labelLocation = Label(self.frameInfo, textvariable= self.varLocation)
        labelIcon = Label(self.frameInfo, text = 'image')

        labelTemp.pack(pady = 5)
        labelLocation.pack(pady = 5)
        labelIcon.pack(pady = 5)
        self.frameInfo.pack()

这是来自weather.py的一些代码

# The pass is there so the app can run without having an error.
    def getConditionIcon(self):
        pass

这里是所有代码的 github:https://github.com/EasyCanadianGamer/Python-Weather-App

我检查了文档,但没有明确说明如何获取图标 url 并更新它。这是 Weatherapi 文档:https://www.weatherapi.com/docs/

python tkinter weather-api
1个回答
1
投票

您可以像获取条件文本一样获取图标URL,并使用

requests.get()
获取图标数据:

def getConditionIcon(self):
    condition = self.getCurrentData("condition")
    icon_url = f"http:{condition['icon']}"
    try:
        icon_data = requests.get(icon_url).content
    except Exception as ex:
        print(ex)
        icon_data = None
    return icon_data

然后您可以将图标数据传递给

tkinter.PhotoImage()
来创建图像对象:

weather = Weather(...)  # pass the location you want
image = tkinter.PhotoImage(data=weather.getConditionIcon())

请注意,如果图标图像不是PNG图像,您可能需要使用

Pillow
模块将图标数据转换为图像。

© www.soinside.com 2019 - 2024. All rights reserved.