
import matplotlib.pyplot as pltimport matplotlib.animation as animationimport datetime# 目标时间target = datetime.datetime(2026, 2, 17, 0, 0, 0)# 创建图形fig, ax = plt.subplots(figsize=(10, 4))ax.axis('off')fig.patch.set_facecolor('#0d0d23')ax.set_facecolor('#0d0d23')# 标题title = ax.text(0.5, 0.75, f"Countdown to New Year",ha='center', va='center', fontsize=22, color='gold', fontweight='bold')# 倒计时数字(大字)text = ax.text(0.5, 0.45, '', ha='center', va='center', fontsize=20,color='white', fontfamily='monospace', fontweight='bold')# 单位提示(小字)units = ax.text(0.5, 0.25,'Days Hours Minutes Seconds',ha='center', va='center', fontsize=14, color='lightgray')def update(frame):# 每次更新都重新计算剩余时间now = datetime.datetime.now()delta = target - nowif delta.total_seconds() > 0:total_sec = int(delta.total_seconds())days = total_sec // (24*3600)hours = (total_sec % (24*3600)) // 3600minutes = (total_sec % 3600) // 60seconds = total_sec % 60# 格式化为 DD : HH : MM : SScountdown_str = f"{days:03d}days : {hours:02d}h : {minutes:02d}m : {seconds:02d}s"text.set_text(countdown_str)text.set_color('cyan' if seconds % 2 == 0 else 'lightgreen') # 轻微闪烁效果else:text.set_text("HAPPY NEW YEAR!")text.set_color('gold')units.set_text("")return text, units# 每1000ms(1秒)刷新一次;repeat=False 表示播完不循环anim = animation.FuncAnimation(fig, update, interval=1000, blit=True, repeat=False)plt.tight_layout()plt.show()
anim = animation.FuncAnimation(fig, update, interval=1000, blit=True, repeat=False)参数 | 含义 |
|---|---|
| 要刷新的 Figure 对象 |
| 回调函数 |
| 刷新间隔 1000ms = 1 秒 |
| 开启“局部重绘”优化 |
| 倒计时结束后停止 |
推荐文章