在 python/Tkinter 中显示来自 URL 的图像 [英] Displaying Image from URL in python/Tkinter

查看:47
本文介绍了在 python/Tkinter 中显示来自 URL 的图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个天气应用程序并添加一些我正在考虑添加天气地图的香料,所以到达 https://openweathermap.org/api/weathermaps 并获得带有图像的 URL.我研究了许多在 Tkinter Widget 上显示该图像的方法,但没有一个有效.它显示图像的大小,但不显示图像本身.这是我的代码.非常感谢.

I am working on a weather app and to add some spice I was thinking on adding a Weather Map, so reached over to https://openweathermap.org/api/weathermaps and got a URL with the image. I researched for many methods on displaying that image on a Tkinter Widget but none of them work. It displays the size of the image but not the image itself. This is my code. Thank you very much.

from tkinter import *
from PIL import ImageTk, Image
import requests
import urllib.request
import base64

root = Tk()
root.title("Weather")


link = "https://tile.openweathermap.org/map/pressure_new/0/0/0.png?appid={APIkey}"

class WebImage:
     def __init__(self,url):
          u = urllib.request.urlopen(url)
          raw_data = u.read()
          u.close()
          self.image = PhotoImage(data=base64.encodebytes(raw_data))

     def get(self):
          return self.image

img = WebImage(link_6).get()
imagelab = Label(root, image = img)
imagelab.grid(row = 0, column = 0)

root.mainloop()

推荐答案

如果链接中的图像是 PNG,您的代码工作正常.可能是链接中的图像是 tkinter.PhotoImage 不支持的 JPEG.

You code works fine if the image in the link is PNG. May be the image in the link is JPEG which is not supported by tkinter.PhotoImage.

您可以使用支持各种图像格式的Pillow模块:

You can use Pillow module which supports various image formats:

import tkinter as tk
import urllib.request
#import base64
import io
from PIL import ImageTk, Image

root = tk.Tk()
root.title("Weather")

link = "https://openweathermap.org/themes/openweathermap/assets/img/logo_white_cropped.png"

class WebImage:
    def __init__(self, url):
        with urllib.request.urlopen(url) as u:
            raw_data = u.read()
        #self.image = tk.PhotoImage(data=base64.encodebytes(raw_data))
        image = Image.open(io.BytesIO(raw_data))
        self.image = ImageTk.PhotoImage(image)

    def get(self):
        return self.image

img = WebImage(link).get()
imagelab = tk.Label(root, image=img)
imagelab.grid(row=0, column=0)

root.mainloop()

这篇关于在 python/Tkinter 中显示来自 URL 的图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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