首页 > 解决方案 > 如何在python中不断使用Tkinter一张一张地滑动图像?

问题描述

我正在用 Python 学习 Tkinter。我正在尝试在没有按钮的情况下不断地一张一张地制作图像的幻灯片更换器。图像将在延迟一段时间后自动更改。我正在使用 for 循环从我的目录中迭代我的图像文件,但是当我在目录中只提供一个图像时,图像会在 tkinter 弹出显示上闪烁,但是当我提供多个图像时,我的图像是'没有出现在显示屏上。

import os
from tkinter import *
from PIL import Image,ImageTk
import time
path = "Album"
root = Tk()
root.geometry("576x432")

location  = os.listdir("Album")
print(location)
#Output: ['1 (1).jpg', '1 (2).jpg', '1 (3).jpg', '1 (4).jpg', '1 (5).jpg', 'not out.png', 'out.png', 'pending.png']



for iteam in location:
    image1 = Image.open(f"Album/{iteam}")
    photo1 = ImageTk.PhotoImage(image1)
    photo_label1 = Label(image=photo1)
    photo_label1.pack()
    time.sleep(2)
root.mainloop()

有没有办法做到这一点?

标签: pythontkinteroperating-system

解决方案


正如我之前所说,我在这里收集了代码,以在每 2 秒(2000 毫秒)后重复显示图像。我已经最大限度地评论了下面的代码,以便在旅途中更容易理解。

from tkinter import *
from PIL import Image, ImageTk
import time
from glob import glob
from tkinter import filedialog

root = Tk()
root.geometry("576x432")

path = filedialog.askdirectory(title='Choose the directory with images') #get the directory path
location1  = glob(f'{path}//*.png') #get the path of all png image
location2 = glob(f'{path}//*.jpg') #get the path of all jpg image
final_loc = location1 + location2 #combine those list to a final main list
print(final_loc) #check the list
#Output: ['1 (1).jpg', '1 (2).jpg', '1 (3).jpg', '1 (4).jpg', '1 (5).jpg', 'not out.png', 'out.png', 'pending.png']

i = 0 #set the index value to 0
def show():
    global i #so that the value of i changes on global scope
    try: 
        image1 = Image.open(final_loc[i]) #open the index-th image
        photo1 = ImageTk.PhotoImage(image1)
        photo_label1.config(image=photo1) #using config so the image doesnt overlap
        photo_label1.img = photo1 #keeping a reference
        i += 1 #increasing the index number
    except IndexError: #if no more items in the list to index
        i = 0 #set index back to 0
    finally:
        root.after(2000,show) #keep repeating the function every 2 sec or 2000 ms

photo_label1 = Label(root) #create a label, later to be editeed
photo_label1.pack()

show() #call the function

root.mainloop()

我已经使示例尽可能动态。您可以选择目录,我更改osglob,我相信这对这种情况有好处。您可以更进一步并添加另一个按钮来停止“幻灯片放映”。

与 tkinter一起使用并不好,sleep()因为它会在等待时冻结您的 GUI。所以改为使用 tkinter 方法after(ms,func)

after()方法主要有两个参数:

  • ms- 函数应该运行的时间,以毫秒(ms)为单位
  • func- 在给定 ms 完成后运行的函数。

虽然更大的图像可能不适合您的屏幕,但这是一个全新的 Q,无论如何我已经在这里问过类似的Q。


推荐阅读