Python 基于 pygame 實現(xiàn)輪播圖動畫效果
Python 基于 pygame 實現(xiàn)輪播圖動畫
輪播圖動畫是在一個固定的區(qū)域內(nèi)循環(huán)展示多個圖片或者內(nèi)容項。在 Python 中可以適應第三方庫pygame來實現(xiàn)輪播圖動畫的效果,使用pygame前需確保其已經(jīng)安裝。
如下是代碼示例:
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))
# 創(chuàng)建定時器事件
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
# 開啟時間循環(huán)
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == CHANGE_IMAGE_EVENT:
# 定時器事件觸發(fā)時切換到下一張圖片
current_image_index = (current_image_index + 1) % len(image_files)
image = pygame.image.load(image_files[current_image_index])
# # 調(diào)整圖片大小以適應窗口尺寸
image = pygame.transform.scale(image, (screen_width, screen_height))
# 在窗口上繪制當前的圖片
screen.blit(image, (0, 0))
pygame.display.flip()
pygame.quit()
# 主函數(shù)調(diào)用
if __name__ == "__main__":
# 圖片文件路徑列表
image_files = ['img/gou1.jpg', 'img/gou2.jpg', 'img/mao1.jpg', 'img/mao2.jpg']
# 數(shù)開始輪播圖動畫
carousel_animation(image_files)上述代碼通過carousel_animation函數(shù)實現(xiàn)了一個輪播圖動畫的效果,函數(shù)接收圖片文件路徑列表image_files作為參數(shù),在函數(shù)內(nèi)部通過pygame.time.set_timer方法來設置定時器事件,在主循環(huán)中,不斷地檢測是否觸發(fā)了定時器事件,如果觸發(fā)了,就更新當前圖片索引值,從而實現(xiàn)圖片的輪播效果。
需要注意的是,上述示例中的圖像路徑需要根據(jù)實際情況進行替換。
擴展:
Python 實現(xiàn)圖片輪播及音樂循環(huán)播放
根據(jù)自己的實際情況修改Path參數(shù)。
遇到的問題:如果文件夾下存在圖片損壞會停止播放,為了播放順暢,可手動刪除已損壞圖片。
# -*- 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 # 當前照片計數(shù)
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() # 創(chuàng)建窗口
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) # 創(chuàng)建音樂播放線程
t = threading.Thread(target=image_change) # 創(chuàng)建圖片切換線程
# python 可以通過 threading module 來創(chuàng)建新的線程,然而在創(chuàng)建線程的線程(父線程)關(guān)閉之后,相應的子線程可能卻沒有關(guān)閉
# 需要把 setDaemon 函數(shù)放在 start 函數(shù)前面解決此問題
# m.setDaemon(True)
# m.start() # 啟動線程
t.start() # 啟動線程
root.mainloop() # 窗口循環(huán)到此這篇關(guān)于Python 基于 pygame 實現(xiàn)輪播圖動畫效果的文章就介紹到這了,更多相關(guān)Python 輪播圖動畫內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python數(shù)據(jù)處理-導入導出excel數(shù)據(jù)
這篇文章主要介紹了Python數(shù)據(jù)處理-導入導出excel數(shù)據(jù),Python的一大應用就是數(shù)據(jù)分析了,而數(shù)據(jù)分析中,經(jīng)常碰到需要處理Excel數(shù)據(jù)的情況。這里做一個Python處理Excel數(shù)據(jù)的總結(jié),需要的小伙伴可以參考一下2022-01-01
python 和c++實現(xiàn)旋轉(zhuǎn)矩陣到歐拉角的變換方式
今天小編就為大家分享一篇python 和c++實現(xiàn)旋轉(zhuǎn)矩陣到歐拉角的變換方式,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-12-12
python+selenium實現(xiàn)12306模擬登錄的步驟
這篇文章主要介紹了python+selenium實現(xiàn)12306模擬登錄的步驟,幫助大家更好的理解和使用python,感興趣的朋友可以了解下2021-01-01
七個生態(tài)系統(tǒng)核心庫[python自學收藏]
無論你是想快速入手Python,還是想成為數(shù)據(jù)分析大神或者機器學習大佬,亦或者對Python代碼進行優(yōu)化,本文的python庫都能為你提供一些幫助2021-08-08
tkinter如何實現(xiàn)label超鏈接調(diào)用瀏覽器打開網(wǎng)址
這篇文章主要介紹了tkinter如何實現(xiàn)label超鏈接調(diào)用瀏覽器打開網(wǎng)址問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-01-01

