#!/usr/bin/python3
# ward 2024/4/18 coding Electronic photo album
#
#
import os
import tkinter as tk
from PIL import Image, ImageTk
import time
class DigitalPhotoFrame:
def __init__(self, root, image_folder, interval=5):
self.root = root
self.image_folder = image_folder
self.interval = interval
# 判断指定文件夹下以 “.JPG...”为结尾的文件,赋值给image_files
self.image_files = [f for f in os.listdir(image_folder) if f.endswith(('.JPG', '.jpg', '.jpeg', '.png', '.gif'))]
self.current_image_index = 0
self.image_label = tk.Label(root)
self.image_label.pack()
self.show_next_image()
def show_next_image(self):
# 这里是拼凑一个图片完整路径,兼容Windows和Linux环境
image_path = os.path.join(self.image_folder, self.image_files[self.current_image_index])
# 打开图片
image = Image.open(image_path)
# 定义相片大小
# image = image.resize((1080, 960))
# 转换图像
photo = ImageTk.PhotoImage(image)
self.image_label.config(image=photo)
self.image_label.image = photo
# 这里是类似一个for循环作用,遍历文件夹下所有图片
self.current_image_index = (self.current_image_index + 1) % len(self.image_files)
# 重复调用,实现循环显示文件夹内图片,每隔一定时间刷新一次窗口
self.root.after(self.interval * 1000, self.show_next_image)
if __name__ == "__main__":
# 创建主窗口
root = tk.Tk()
# 添加一个label,把label里的文字放在中间
label = tk.Label(root, text="This is my electronic photo album", justify="center", anchor="center")
label.pack()
# 这里定义窗口名字
root.title("photo v1.0")
# 定义初始窗口大小
root.geometry("1920x1080")
# 指定图片文件夹的路径
image_folder = "C:\\ward\\photo"
# 设置切换图片的间隔时间(秒)
interval = 5
# 创建 DigitalPhotoFrame 对象
photo_frame = DigitalPhotoFrame(root, image_folder, interval)
root.mainloop()
python实现 电子相册 效果,循环播放指定文件夹下的图片
最新推荐文章于 2024-06-09 06:15:36 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)