[英]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.