欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Python 基于 pygame 實(shí)現(xiàn)輪播圖動(dòng)畫(huà)效果

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

Python 基于 pygame 實(shí)現(xiàn)輪播圖動(dòng)畫(huà)

輪播圖動(dòng)畫(huà)是在一個(gè)固定的區(qū)域內(nèi)循環(huán)展示多個(gè)圖片或者內(nèi)容項(xiàng)。在 Python 中可以適應(yīng)第三方庫(kù)pygame來(lái)實(shí)現(xiàn)輪播圖動(dòng)畫(huà)的效果,使用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)建定時(shí)器事件
    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
    # 開(kāi)啟時(shí)間循環(huán)
    while running:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
            elif event.type == CHANGE_IMAGE_EVENT:
                # 定時(shí)器事件觸發(fā)時(shí)切換到下一張圖片
                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ù)開(kāi)始輪播圖動(dòng)畫(huà)
    carousel_animation(image_files)

上述代碼通過(guò)carousel_animation函數(shù)實(shí)現(xiàn)了一個(gè)輪播圖動(dòng)畫(huà)的效果,函數(shù)接收?qǐng)D片文件路徑列表image_files作為參數(shù),在函數(shù)內(nèi)部通過(guò)pygame.time.set_timer方法來(lái)設(shè)置定時(shí)器事件,在主循環(huán)中,不斷地檢測(cè)是否觸發(fā)了定時(shí)器事件,如果觸發(fā)了,就更新當(dāng)前圖片索引值,從而實(shí)現(xiàn)圖片的輪播效果。

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

擴(kuò)展:

Python 實(shí)現(xiàn)圖片輪播及音樂(lè)循環(huán)播放

根據(jù)自己的實(shí)際情況修改Path參數(shù)。
遇到的問(wèn)題:如果文件夾下存在圖片損壞會(huì)停止播放,為了播放順暢,可手動(dòng)刪除已損壞圖片。

# -*- 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 制作一個(gè)電子相冊(cè)
"""
# 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():
    """播放音樂(lè)。"""
    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)  # 對(duì)路徑與文件進(jìn)行拼接
            list2.append(s)
        while True:
            for n in list2:
                # 獲取每一首歌的時(shí)長(zhǎng)
                path = n
                audio = MP3(n)
                pygame.mixer.init()  # 初始化所有引入的模塊
                pygame.mixer.music.load(path)  # 載入音樂(lè),音樂(lè)可以是 ogg、mp3 等格式
                pygame.mixer.music.play()  # 播放載入的音樂(lè)
                time.sleep(int(audio.info.length))  # 獲取每一首歌曲的時(shí)長(zhǎng),使程序存活的時(shí)長(zhǎng)等于歌曲時(shí)長(zhǎng)
    except Exception as e:
        print("Exception: %s" % e)
resolution = (1366, 768)  # 分辨率
Path = r'D:/nlpPredict/SentenceSimilarity/daj/'  # 相冊(cè)路徑
Interval = 5  # 播放間隔.單位:s
Index = 0  # 當(dāng)前照片計(jì)數(shù)
title = "電子相冊(cè)"  # 窗口標(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 打開(kāi)圖片
panel = tk.Label(root, image=img)  # Label 自適應(yīng)圖片大小
panel.pack(side="bottom", fill="both", expand="yes")
def callback(e):
    """手動(dòng)切換圖片。"""
    try:
        global Index
        for i, x in enumerate(files):
            # 判斷文件是否存在
            if not os.path.isfile(Path + '%s' % x):
                break
            if i != Index:  # 跳過(guò)已播放的圖片
                continue
            print('手動(dòng)處理圖片', x, Index)  # python 3.5
            # print(unicode('手動(dòng)處理圖片 %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)  # 點(diǎn)擊窗口切換下一張圖片
def image_change():
    """自動(dòng)切換圖片。"""
    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:  # 跳過(guò)已播放的圖片
                    continue
                print('自動(dòng)處理圖片', x, Index)  # python 3.5
                # print(unicode('自動(dòng)處理圖片 %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)建音樂(lè)播放線程
t = threading.Thread(target=image_change)  # 創(chuàng)建圖片切換線程
# python 可以通過(guò) threading module 來(lái)創(chuàng)建新的線程,然而在創(chuàng)建線程的線程(父線程)關(guān)閉之后,相應(yīng)的子線程可能卻沒(méi)有關(guān)閉
# 需要把 setDaemon 函數(shù)放在 start 函數(shù)前面解決此問(wèn)題
# m.setDaemon(True)
# m.start()  # 啟動(dòng)線程
t.start()  # 啟動(dòng)線程
root.mainloop()  # 窗口循環(huán)

到此這篇關(guān)于Python 基于 pygame 實(shí)現(xiàn)輪播圖動(dòng)畫(huà)效果的文章就介紹到這了,更多相關(guān)Python 輪播圖動(dòng)畫(huà)內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論