如何在 Tkinter 中显示图像(来自 URL)

时间:2021-03-30 18:21:14

标签: python image url tkinter

我想在 Tkinter 中显示来自 URL 的图像。 这是我目前的功能:

def getImageFromURL(url):
    print('hai')
    raw_data = urlopen(url).read()
    im = Image.open(BytesIO(raw_data))
    image = ImageTk.PhotoImage(im)
    return image

我使用这个函数的代码是:

print(imgJSON[currentIndex])
img = getImageFromURL(imgJSON[currentIndex])
imagelab = tk.Label(self, image=img)
imagelab.image = img
imagelab.pack()

然而,代码使 tkinter 窗口崩溃(无响应),但没有错误。我该如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

您可以使用线程从 Internet 获取图像并使用 tkinter 虚拟事件在图像加载时通知 tkinter 应用程序。

以下是示例代码:

import threading
import tkinter as tk
from urllib.request import urlopen
from PIL import ImageTk

def getImageFromURL(url, controller):
    print('hai')
    try:
        controller.image = ImageTk.PhotoImage(file=urlopen(url))
        # notify controller that image has been downloaded
        controller.event_generate("<<ImageLoaded>>")
    except Exception as e:
        print(e)

class App(tk.Tk):
    def __init__(self):
        super().__init__()

        self.imagelab = tk.Label(self, text="Loading image from internet ...", width=50, height=5)
        self.imagelab.pack()

        self.bind("<<ImageLoaded>>", self.on_image_loaded)

        # start a thread to fetch the image
        url = "https://batman-news.com/wp-content/uploads/2017/11/Justice-League-Superman-Banner.jpg"
        threading.Thread(target=getImageFromURL, args=(url, self)).start()

    def on_image_loaded(self, event):
        self.imagelab.config(image=self.image, width=self.image.width(), height=self.image.height())

App().mainloop()