亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

Python 基于 pygame 實現(xiàn)輪播圖動畫效果

 更新時間:2024年03月13日 16:29:50   作者:碼農(nóng)強仔  
在Python中可以適應(yīng)第三方庫pygame來實現(xiàn)輪播圖動畫的效果,使用pygame前需確保其已經(jīng)安裝,本文通過實例代碼介紹Python 基于 pygame 實現(xiàn)輪播圖動畫效果,感興趣的朋友跟隨小編一起看看吧

Python 基于 pygame 實現(xiàn)輪播圖動畫

輪播圖動畫是在一個固定的區(qū)域內(nèi)循環(huán)展示多個圖片或者內(nèi)容項。在 Python 中可以適應(yīng)第三方庫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()
    # 設(shè)置窗口尺寸
    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)整圖片大小以適應(yīng)窗口尺寸
                image = pygame.transform.scale(image, (screen_width, screen_height))
        # 在窗口上繪制當(dāng)前的圖片
        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方法來設(shè)置定時器事件,在主循環(huán)中,不斷地檢測是否觸發(fā)了定時器事件,如果觸發(fā)了,就更新當(dāng)前圖片索引值,從而實現(xiàn)圖片的輪播效果。

需要注意的是,上述示例中的圖像路徑需要根據(jù)實際情況進(jìn)行替換。

擴展:

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)  # 對路徑與文件進(jìn)行拼接
            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  # 當(dāng)前照片計數(shù)
title = "電子相冊"  # 窗口標(biāo)題
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  # 設(shè)定 ANTIALIAS ,即抗鋸齒
root = tk.Tk()  # 創(chuàng)建窗口
root.title(title)  # 設(shè)置窗口標(biāo)題
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)  # 重新設(shè)置大小
img = ImageTk.PhotoImage(img_out)  # 用 PhotoImage 打開圖片
panel = tk.Label(root, image=img)  # Label 自適應(yīng)圖片大小
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)閉之后,相應(yīng)的子線程可能卻沒有關(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)文章

最新評論