[英]How can I Iterate through a list of Images and Display them in Tkinter
所以,我的目標是在 Tkinter 中創建一種幻燈片。 我有一個圖像列表,例如 Images = ["1.png", "2.png", ...],我希望能夠遍歷列表並在 Tkinter window 中顯示每個圖像,這個概念很簡單如下:
我已經設法使用按鈕按下來迭代圖像,但是,我不想單擊按鈕,因為它是為了模仿幻燈片,我還嘗試循環 function 但 time.sleep() function 不會延遲以正確的方式,因為 Tkinter 的行為方式。
我設法使用來自這里的主要源代碼來實現上述目標,我將不勝感激實現上述目標。
我的代碼:
from tkinter import *
from PIL import ImageTk, Image
Window = Tk()
Window.geometry("1920x1080")
Window.resizable(0, 0)
Label1 = Label(Window)
Label1.pack()
Images = iter(["1.png", "2.png", "3.png", "4.png", "5.png",
"6.png", "7.png", "8.png", "9.png", "10.png"])
def Next_Image(Val):
try:
Image1 = next(Images)
except StopIteration:
return
Image1 = ImageTk.PhotoImage(Image.open(Image1))
Label1.Image = Image1
Label1["image"] = Image1
Button1 = Button(text = "Next image", command =
lambda:Next_Image(1))
Button1.place(x = 50, y = 50)
Next_Image(1)
Window.mainloop()
我也嘗試使用.after()
,但是,它沒有顯示每張圖像,它會立即從第一張圖像跳到最后一張圖像,並帶有復合延遲。
for x in range(1, 11):
Window.after(1000, lambda : Next_Image(1))
您需要創建一個 function 從列表中獲取圖像並顯示它,然后使用after
在一秒鍾內再次調用自身。 你的主程序需要只調用一次,然后它會一直運行,直到它做完所有事情。
這是一個為簡單起見使用文本字符串的工作示例,但如何修改它以使用圖像應該很明顯。
import tkinter as tk
images = iter(["1.png", "2.png", "3.png", "4.png", "5.png",
"6.png", "7.png", "8.png", "9.png", "10.png"])
def next_image():
try:
image = next(images)
label.configure(text=image)
root.after(1000, next_image)
except StopIteration:
return
root = tk.Tk()
label = tk.Label(root, width = 40, height=4)
label.pack()
next_image()
root.mainloop()
您可以使用.after()
定期切換圖像:
from itertools import cycle
...
# use cycle() instead of iter()
Images = cycle([f"{i}.png" for i in range(1, 5)])
...
def next_image():
# use next() to get next image in the cycle list
Label1.image = ImageTk.PhotoImage(file=next(Images))
Label1['image'] = Label1.image
# switch image again after 1 second
Label1.after(1000, next_image)
next_image() # start the loop
Window.mainloop()
這行得通,謝謝@acw1668 和@Bryan Oakley。
from tkinter import *
from PIL import ImageTk, Image
Window = Tk()
Window.geometry("1920x1080")
Window.resizable(0, 0)
Label1 = Label(Window)
Label1.pack()
Images = iter(["1.png", "2.png", "3.png", "4.png", "5.png", "6.png",
"7.png", "8.png", "9.png", "10.png"])
def Next_Image(Val):
try:
Image1 = next(Images)
except StopIteration:
return
Image1 = ImageTk.PhotoImage(Image.open("BuyingConfig\\" + Image1))
Label1.Image = Image1
Label1["image"] = Image1
Window.after(3000, lambda:Next_Image(1))
Window.after(0, lambda:Next_Image(1))
Window.mainloop()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.