使用以下代碼,我想顯示.\Datasets\image_datasets\problem_datasets專案中相對路徑中的影像,但我無法使用 tkinter 執行此操作,而是在同一個 UI 視窗中顯示所有影像,我希望這些影像像幀流一樣顯示為一個視頻,你能幫我理解為什么我沒有得到預期的輸出。
代碼 :
import tkinter as tk
from PIL import ImageTk, Image
from matplotlib import image
from numpy import imag
import matplotlib.pyplot as plt
import glob
root = tk.Tk()
root.title("Test app")
images = [file for file in glob.glob('.\\Datasets\\image_datasets\\problem_datasets\\*.jpg')]
for path in images:
img = ImageTk.PhotoImage(Image.open(path))
lab = tk.Label(root,image=img)
lab.photo = img
lab.pack()
root.mainloop()

uj5u.com熱心網友回復:
您在 for 回圈的每次迭代中都創建了新標簽。相反,您應該在 for 回圈之前創建一次標簽并在其中更新其影像。
time.sleep()但是在 tkinter 應用程式中不推薦使用回圈,建議.after()改用:
import tkinter as tk
from PIL import ImageTk, Image
import glob
root = tk.Tk()
root.title("Test app")
images = glob.glob('./Datasets/image_datasets/problem_datasets/*.jpg')
# create the label for showing the images
lab = tk.Label(root)
lab.pack()
def show_image(i=0):
if i < len(images):
img = ImageTk.PhotoImage(file=images[i])
# update image
lab.config(image=img)
lab.photo = img # save reference of image to avoid garbage collection
# can change 10(ms) to other value to suit your case
root.after(10, show_image, i 1)
show_image() # start showing the images
root.mainloop()
uj5u.com熱心網友回復:
幾點:
- 你不需要
lab.photo = img - 您需要在回圈外部定義和打包標簽,然后覆寫內部的影像屬性,否則每次迭代都會創建新標簽
- 我建議使用
os.sep而不是硬編碼的檔案夾分隔符\\來獨立于作業系統 - 要實際看到過渡,您需要
time.sleep或類似的 - 我的示例將凍結 GUI,如果您希望它在啟動影像轉換/“視頻”后具有反應性,則必須實作執行緒
import tkinter as tk
from PIL import ImageTk, Image
from matplotlib import image
from numpy import imag
import matplotlib.pyplot as plt
import glob
import os
import time
root = tk.Tk()
root.title("Test app")
images = [file for file in glob.glob('.' os.sep 'Datasets' os.sep 'image_datasets' os.sep 'problem_datasets' os.sep '*.jpg')]
lab = tk.Label(root)
lab.pack()
for path in images:
_img = ImageTk.PhotoImage(Image.open(path))
lab.config(image=_img)
root.update() # to update the GUI
time.sleep(0.25) # to see the transition
root.mainloop()
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/445443.html
標籤:Python 图片 用户界面 tkinter python成像库
上一篇:來自外部資料庫的資料驗證
