You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python的PySimpleGUI实现GIF播放5秒后自动返回idle状态

实现PySimpleGUI中GIF播放5秒后自动切回Idle状态

要实现点击按钮后播放指定GIF 5秒再切回idle状态,核心是通过时间戳跟踪动画播放时长,在主循环中判断是否达到切换条件。以下是具体修改方案:

修改步骤

  1. 导入time模块,用于获取当前时间戳
  2. 初始化变量记录非idle动画的开始时间
  3. 在按钮点击时记录切换动画的时间点
  4. 主循环中检查时长,超时则切回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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 03:25:13