Python 基于 pygame 实现轮播图动画效果

 更新时间:2024年03月13日 16:29:50   作者:码农强仔  
在Python中可以适应第三方库pygame来实现轮播图动画的效果,使用pygame前需确保其已经安装,本文通过实例代码介绍Python 基于 pygame 实现轮播图动画效果,感兴趣的朋友跟随小编一起看看吧

Python 基于 pygame 实现轮播图动画

轮播图动画是在一个固定的区域内循环展示多个图片或者内容项。在 Python 中可以适应第三方库pygame来实现轮播图动画的效果,使用pygame前需确保其已经安装。
如下是代码示例:

import pygame
def carousel_animation(image_files, screen_width=800, screen_height=600, interval=2000):
    pygame.init()
    # 初始化 Pygame
    pygame.init()
    # 设置窗口尺寸
    screen = pygame.display.set_mode((screen_width, screen_height))
    # 创建定时器事件
    CHANGE_IMAGE_EVENT = pygame.USEREVENT + 1
    pygame.time.set_timer(CHANGE_IMAGE_EVENT, interval)
    # 加载第一张图片
    current_image_index = 0
    image = pygame.image.load(image_files[current_image_index])
    image = pygame.transform.scale(image, (screen_width, screen_height))
    running = True
    # 开启时间循环
    while running:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
            elif event.type == CHANGE_IMAGE_EVENT:
                # 定时器事件触发时切换到下一张图片
                current_image_index = (current_image_index + 1) % len(image_files)
                image = pygame.image.load(image_files[current_image_index])
                # # 调整图片大小以适应窗口尺寸
                image = pygame.transform.scale(image, (screen_width, screen_height))
        # 在窗口上绘制当前的图片
        screen.blit(image, (0, 0))
        pygame.display.flip()
    pygame.quit()
# 主函数调用
if __name__ == "__main__":
    # 图片文件路径列表
    image_files = ['img/gou1.jpg', 'img/gou2.jpg', 'img/mao1.jpg', 'img/mao2.jpg']
    # 数开始轮播图动画
    carousel_animation(image_files)

上述代码通过carousel_animation函数实现了一个轮播图动画的效果,函数接收图片文件路径列表image_files作为参数,在函数内部通过pygame.time.set_timer方法来设置定时器事件,在主循环中,不断地检测是否触发了定时器事件,如果触发了,就更新当前图片索引值,从而实现图片的轮播效果。

需要注意的是,上述示例中的图像路径需要根据实际情况进行替换。

扩展:

Python 实现图片轮播及音乐循环播放

根据自己的实际情况修改Path参数。
遇到的问题:如果文件夹下存在图片损坏会停止播放,为了播放顺畅,可手动删除已损坏图片。

# -*- coding: utf-8 -*-
"""
Created on 2019/8/20
@author: eln
@requirements: PyCharm 2017.2; Python 3.5.6 |Anaconda 4.1.1 (64-bit)
@decription: 用 Python 制作一个电子相册
"""
# pip install pillow pygame mutagen
import os
import sys
import threading
import tkinter as tk
import time
from PIL import ImageTk, Image
import pygame
from mutagen.mp3 import MP3
def playmusic():
    """播放音乐。"""
    Path = r'music\\'
    try:
        list1 = os.listdir(Path)  # 获取指定路径下所有的 mp3 文件
        for x in list1:
            if not (x.endswith('.mp3')):
                list1.remove(x)
        list2 = []
        for i in list1:
            s = os.path.join(Path, i)  # 对路径与文件进行拼接
            list2.append(s)
        while True:
            for n in list2:
                # 获取每一首歌的时长
                path = n
                audio = MP3(n)
                pygame.mixer.init()  # 初始化所有引入的模块
                pygame.mixer.music.load(path)  # 载入音乐,音乐可以是 ogg、mp3 等格式
                pygame.mixer.music.play()  # 播放载入的音乐
                time.sleep(int(audio.info.length))  # 获取每一首歌曲的时长,使程序存活的时长等于歌曲时长
    except Exception as e:
        print("Exception: %s" % e)
resolution = (1366, 768)  # 分辨率
Path = r'D:/nlpPredict/SentenceSimilarity/daj/'  # 相册路径
Interval = 5  # 播放间隔.单位:s
Index = 0  # 当前照片计数
title = "电子相册"  # 窗口标题
def getfiles():
    """获取图片文件名。"""
    files = os.listdir(Path)
    for x in files:
        if not (x.endswith('.jpg') or x.endswith('.JPG') or x.endswith('.png')):
            files.remove(x)
    return files
files = getfiles()
print(files)
scaler = Image.ANTIALIAS  # 设定 ANTIALIAS ,即抗锯齿
root = tk.Tk()  # 创建窗口
root.title(title)  # 设置窗口标题
img_in = Image.open(Path + files[0])  # 加载第一张图片
# img_in = Image.open("load.jpg")  # 加载第一张图片
w, h = img_in.size  # 获取图片大小
size_new = (int(w * resolution[1] / h), resolution[1])
img_out = img_in.resize(size_new, scaler)  # 重新设置大小
img = ImageTk.PhotoImage(img_out)  # 用 PhotoImage 打开图片
panel = tk.Label(root, image=img)  # Label 自适应图片大小
panel.pack(side="bottom", fill="both", expand="yes")
def callback(e):
    """手动切换图片。"""
    try:
        global Index
        for i, x in enumerate(files):
            # 判断文件是否存在
            if not os.path.isfile(Path + '%s' % x):
                break
            if i != Index:  # 跳过已播放的图片
                continue
            print('手动处理图片', x, Index)  # python 3.5
            # print(unicode('手动处理图片 %s %d' % (x, Index), "utf8", errors="ignore"))  # python 2.7.15
            img_in = Image.open(Path + '%s' % x)
            print(img_in)
            w, h = img_in.size
            size_new = (int(w * resolution[1] / h), resolution[1])
            img_out = img_in.resize(size_new, scaler)
            img2 = ImageTk.PhotoImage(img_out)
            panel.configure(image=img2)
            panel.image = img2
            Index += 1
            if Index >= len(files):
                Index = 0
            break
    except Exception as e:
        print("Exception: %s " % e)
        sys.exit(1)
# root.bind("<Return>", callback)
root.bind("<Button-1>", callback)  # 点击窗口切换下一张图片
def image_change():
    """自动切换图片。"""
    try:
        global Index
        time.sleep(3)
        while True:
            for i, x in enumerate(files):
                # 判断文件是否存在
                if not os.path.isfile(Path + '%s' % x):
                    break
                if i != Index:  # 跳过已播放的图片
                    continue
                print('自动处理图片', x, Index)  # python 3.5
                # print(unicode('自动处理图片 %s %d' % (x, Index), "utf8", errors="ignore"))  # python 2.7.15
                img_in = Image.open(Path + '%s' % x)
                w, h = img_in.size
                size_new = (int(w * resolution[1] / h), resolution[1])
                img_out = img_in.resize(size_new, scaler)
                img2 = ImageTk.PhotoImage(img_out)
                panel.configure(image=img2)
                panel.image = img2
                Index += 1
                if Index >= len(files):
                    Index = 0
                time.sleep(Interval)
    except Exception as e:
        print("Exception: %s " % e)
        sys.exit(1)
# m = threading.Thread(target=playmusic)  # 创建音乐播放线程
t = threading.Thread(target=image_change)  # 创建图片切换线程
# python 可以通过 threading module 来创建新的线程,然而在创建线程的线程(父线程)关闭之后,相应的子线程可能却没有关闭
# 需要把 setDaemon 函数放在 start 函数前面解决此问题
# m.setDaemon(True)
# m.start()  # 启动线程
t.start()  # 启动线程
root.mainloop()  # 窗口循环

到此这篇关于Python 基于 pygame 实现轮播图动画效果的文章就介绍到这了,更多相关Python 轮播图动画内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • Python反向传播实现线性回归步骤详细讲解

    Python反向传播实现线性回归步骤详细讲解

    回归是监督学习的一个重要问题,回归用于预测输入变量和输出变量之间的关系,特别是当输入变量的值发生变化时,输出变量的值也随之发生变化。回归模型正是表示从输入变量到输出变量之间映射的函数
    2022-10-10
  • TensorFlow模型保存和提取的方法

    TensorFlow模型保存和提取的方法

    这篇文章主要为大家详细介绍了TensorFlow模型保存和提取的方法,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2018-03-03
  • Django使用Channels实现WebSocket的方法

    Django使用Channels实现WebSocket的方法

    WebSocket是一种在单个TCP连接上进行全双工通讯的协议。WebSocket允许服务端主动向客户端推送数据。这篇文章主要介绍了Django使用Channels实现WebSocket,需要的朋友可以参考下
    2019-07-07
  • Python使用Ollama API的详细代码示例

    Python使用Ollama API的详细代码示例

    这篇文章主要介绍了如何在Python中使用OllamaAPI,涵盖了从环境准备、使用方法到高级功能的全面指南,无论是初学者还是经验丰富的开发者都能从中受益,需要的朋友可以参考下
    2025-02-02
  • Python requirements.txt使用小结

    Python requirements.txt使用小结

    requirements.txt是Python项目中用于记录项目依赖包及其版本信息的文本文件,类似于Node.js的或Java的pom.xml,下面就来详细的介绍一下requirements.txt使用,感兴趣的可以了解一下
    2025-11-11
  • Python代码生成视频的缩略图的实例讲解

    Python代码生成视频的缩略图的实例讲解

    在本篇文章里小编给大家正里的是一篇关于Python代码生成视频的缩略图的实例讲解,对此有需要的朋友们可以跟着学习下。
    2019-12-12
  • 如何保证Python代码质量,Python测试与调试方面的经验和心得

    如何保证Python代码质量,Python测试与调试方面的经验和心得

    本文分享了作者在学习Python测试与调试方面的经验和心得,涵盖了Python测试框架(如unittest、pytest)、测试覆盖率、单元测试、集成测试、调试技巧、异常处理等内容,还对比了Python与Rust在测试和调试方面的差异
    2026-05-05
  • python实现日历效果

    python实现日历效果

    这篇文章主要为大家详细介绍了python实现日历效果,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2021-08-08
  • PyCharm远程调试代码配置以及运行参数设置方式

    PyCharm远程调试代码配置以及运行参数设置方式

    这篇文章主要介绍了PyCharm远程调试代码配置以及运行参数设置方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
    2024-01-01
  • 跟老齐学Python之通过Python连接数据库

    跟老齐学Python之通过Python连接数据库

    现在在做python的时候需要用到数据库,于是自己重新整理了一下数据库的知识,并且熟悉了python中MysqlDB模块的功能和函数等接口,现在系统地来总结一下吧
    2014-10-10

最新评论