python实现 电子相册 效果,循环播放指定文件夹下的图片

本文介绍了一个使用Python和Tkinter库创建的动态电子相册应用,通过循环显示指定文件夹内的图片,每隔一段时间自动切换。
摘要由CSDN通过智能技术生成
#!/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()
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值