写一程序实现图片自动随机切换
时间: 2023-07-18 10:42:12 浏览: 101
图片自动切换
好的,以下是一种实现图片自动随机切换的 Python 代码:
```python
import os
import random
import time
from PIL import Image, ImageTk
import tkinter as tk
# 获取指定文件夹下所有图片的文件名
def get_image_filenames(folder_path):
image_extensions = ['.jpg', '.jpeg', '.png', '.bmp', '.gif']
filenames = []
for filename in os.listdir(folder_path):
extension = os.path.splitext(filename)[1]
if extension.lower() in image_extensions:
filenames.append(os.path.join(folder_path, filename))
return filenames
# 随机选择一个图片文件
def choose_random_image(filenames):
return random.choice(filenames)
# 显示图片
def show_image(image_path, window):
image = Image.open(image_path)
photo = ImageTk.PhotoImage(image)
label = tk.Label(window, image=photo)
label.image = photo
label.pack()
# 主循环
def main_loop(folder_path, window, interval):
filenames = get_image_filenames(folder_path)
while True:
image_path = choose_random_image(filenames)
show_image(image_path, window)
time.sleep(interval)
# 测试代码
if __name__ == '__main__':
folder_path = 'path/to/folder' # 指定图片所在的文件夹路径
interval = 5 # 指定图片切换的间隔时间(秒)
window = tk.Tk()
window.geometry('800x600')
window.title('随机图片切换器')
main_loop(folder_path, window, interval)
```
你可以将 `folder_path` 替换为你想要展示的图片文件夹的路径,然后运行该程序即可实现图片自动随机切换。程序会在窗口中显示一张随机选择的图片,并在指定的时间间隔后自动切换到下一张图片。
阅读全文