所以,我的目標是在 Tkinter 中創建一種幻燈片。我有一個像 Images = ["1.png", "2.png", ...] 這樣的影像串列,我希望能夠遍歷串列并在 Tkinter 視窗中顯示每個影像,概念很簡單如下:
- 顯示影像 1
- 30 秒延遲
- 顯示影像 2
- 30 秒延遲
- 顯示影像 3
我已經設法使用按鈕來迭代影像,但是,我不想點擊按鈕,因為它是為了模仿幻燈片,我也嘗試回圈一個函式,但 time.sleep() 函式不會延遲由于 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))
uj5u.com熱心網友回復:
您需要創建一個函式,將影像從串列中取出并顯示出來,然后使用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()
uj5u.com熱心網友回復:
您可以使用.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()
uj5u.com熱心網友回復:
這有效,謝謝@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()
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/390783.html
