如何用Python的PySimpleGUI实现GIF播放5秒后自动返回idle状态
实现PySimpleGUI中GIF播放5秒后自动切回Idle状态
要实现点击按钮后播放指定GIF 5秒再切回idle状态,核心是通过时间戳跟踪动画播放时长,在主循环中判断是否达到切换条件。以下是具体修改方案:
修改步骤
- 导入
time模块,用于获取当前时间戳 - 初始化变量记录非idle动画的开始时间
- 在按钮点击时记录切换动画的时间点
- 主循环中检查时长,超时则切回idle
修改后的完整代码
import PySimpleGUI as sg import time # 新增:导入时间模块 # storing gifs as base64 idle = b'[base64 encoded gif]' wave = b'[base64 encoded gif]' cheer = b'[base64 encoded gif]' tipjar = b'[base64 encoded gif]' cocktail = b'[base64 encoded gif]' beer = b'[base64 encoded gif]' # Putting all gifs into a list gifs = [idle, wave, cheer, tipjar, cocktail, beer] # Setting up the window and button layout sg.theme('DarkAmber') layout = [[sg.Image(background_color='#00b140', key='-IMAGE-', pad=(0, 0), right_click_menu=[ '&Right', ['Settings', 'Exit']])], [sg.Button('!Wave'), sg.Button('!Cheer'), sg.Button('!TipJar'), sg.Button('!Cocktail'), sg.Button('!Beer')]] window = sg.Window('Animated Avatar', layout, margins=(0, 0), finalize=True) image = window['-IMAGE-'] # Calling the first item in the gifs list gif = gifs[0] start_time = None # 新增:记录非idle动画的开始时间 # Program loop while True: event, values = window.read(timeout=100) if event == sg.WIN_CLOSED or event == 'Exit': break # Button click events to change the gif being presented elif event == '!Wave': gif = gifs[1] start_time = time.time() # 新增:记录当前时间戳 elif event == '!Cheer': gif = gifs[2] start_time = time.time() # 新增:记录当前时间戳 elif event == '!TipJar': gif = gifs[3] start_time = time.time() # 新增:记录当前时间戳 elif event == '!Cocktail': gif = gifs[4] start_time = time.time() # 新增:记录当前时间戳 elif event == '!Beer': gif = gifs[5] start_time = time.time() # 新增:记录当前时间戳 # 新增:检查是否超时,切回idle状态 if gif != gifs[0] and start_time is not None: current_time = time.time() if current_time - start_time >= 5: # 超过5秒则切换 gif = gifs[0] start_time = None # Overall gif animation rules image.update_animation(gif, 500)
代码说明
start_time变量用于存储点击按钮切换动画的时间点- 每次按钮点击时,更新
gif的同时记录当前时间 - 主循环中持续检查:如果当前播放的不是idle,且距离开始时间已过5秒,就将
gif切回idle,并重置start_time - 窗口的
timeout=100保证每100毫秒检查一次时间,确保超时切换的及时性
内容的提问来源于stack exchange,提问作者Farles
相关产品推荐
相关产品推荐

