[英]How do I display an Image (from URL) in Tkinter
我想在 Tkinter 中显示来自 URL 的图像。 这是我目前的 function:
def getImageFromURL(url):
print('hai')
raw_data = urlopen(url).read()
im = Image.open(BytesIO(raw_data))
image = ImageTk.PhotoImage(im)
return image
我使用这个 function 的代码是:
print(imgJSON[currentIndex])
img = getImageFromURL(imgJSON[currentIndex])
imagelab = tk.Label(self, image=img)
imagelab.image = img
imagelab.pack()
但是,代码使 tkinter window 崩溃(无响应),但没有错误。 我将如何解决这个问题?
您可以使用线程从 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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.