在Python/Tkinter中显示来自URL的图像

3

我正在开发一个天气应用程序,为了增加一些趣味性,我考虑添加一个天气地图,所以我访问了 https://openweathermap.org/api/weathermaps,并获取了一个图片的URL。我试图找到多种在Tkinter小部件中显示该图片的方法,但是它们都不起作用。它只显示图片的大小,但没有显示图片本身。这是我的代码。非常感谢。

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()
2个回答

2
如果链接中的图像是PNG格式,您的代码可以正常工作。也许链接中的图像是不受 tkinter.PhotoImage 支持的 JPEG 格式。
您可以使用支持各种图像格式的 Pillow 模块。
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()

虽然它能工作,但当我将所有内容放入一个函数中(以便在按下按钮时显示图像)时,它就无法工作了。我该怎么办? - Lorenzo Hsu
这取决于你在函数中如何实现它。 - acw1668
我原本计划要做以下的事情: ` def submit(): class WebImage: def init(self, url): with urllib.request.urlopen(url) as u: raw_data = u.read() 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=1, column=0)tk.Button(root, text = "提交", command = submit).grid(row = 0, column = 0) ` - Lorenzo Hsu
你需要保存图像的引用:imagelab.image = img - acw1668
我应该在我的代码中的哪里添加"image.image = img"? - Lorenzo Hsu
imagelab创建后。 - acw1668

1

这里试试:

from tkinter import *
from PIL import ImageTk, Image
import requests
from io import BytesIO


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


link = "yourlink/image.jpg"

class WebImage:
     def __init__(self,url):
          u = requests.get(url)
          self.image = ImageTk.PhotoImage(Image.open(BytesIO(u.content)))
          
     def get(self):
          return self.image

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

root.mainloop()

我尝试了你的代码,但是出现了以下错误:TypeError: WebImage()不接受任何参数。当我从WebImage中删除"link"参数时,出现了另一个错误:AttributeError: 'WebImage'对象没有'image'属性。无论如何,还是谢谢你的帮助。 - Lorenzo Hsu
@LorenzoHsu 你可能在__init__()方法中漏掉了url参数。 - JacksonPro

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接