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

2024-06-30 08:27:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我想在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窗口崩溃(没有响应),但没有错误。我该如何解决这个问题


Tags: 代码图像imageurlimgdatarawtkinter
1条回答
网友
1楼 · 发布于 2024-06-30 08:27:44

您可以使用线程从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()

相关问题 更多 >