简体   繁体   English

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

[英]How do I display an Image (from URL) in Tkinter

I want to display an image from a URL in Tkinter.我想在 Tkinter 中显示来自 URL 的图像。 This is my current function:这是我目前的 function:

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

And the code where I am using this function is:我使用这个 function 的代码是:

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

However, the code is making the tkinter window crash (Not Responding), but there are no errors.但是,代码使 tkinter window 崩溃(无响应),但没有错误。 How would I fix this?我将如何解决这个问题?

You can use thread to fetch the image from internet and use tkinter virtual event to notify the tkinter application when the image has been loaded.您可以使用线程从 Internet 获取图像并使用 tkinter 虚拟事件在图像加载后通知 tkinter 应用程序。

Below is an example code:下面是一个示例代码:

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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM