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

如何为嵌入Tkinter的Matplotlib动画添加按钮触发的暂停功能

实现方案

核心通过FuncAnimation内置的暂停/恢复接口配合按钮点击事件实现,修改逻辑和完整代码如下:

核心修改点

  • 新增全局状态变量is_paused记录动画播放状态
  • 编写状态切换回调函数,点击按钮时切换动画状态,同步更新按钮显示文本
  • 新增绑定了回调的Pause按钮控件

完整可运行代码

import tkinter
from matplotlib.backends.backend_tkagg import (
    FigureCanvasTkAgg, NavigationToolbar2Tk)
from matplotlib.backend_bases import key_press_handler
from matplotlib import pyplot as plt, animation
import numpy as np

plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True

root = tkinter.Tk()
root.wm_title("Embedding in Tk")

plt.axes(xlim=(0, 2), ylim=(-2, 2))
fig = plt.Figure(dpi=100)
ax = fig.add_subplot(xlim=(0, 2), ylim=(-1, 1))
line, = ax.plot([], [], lw=2)

canvas = FigureCanvasTkAgg(fig, master=root)
canvas.draw()

toolbar = NavigationToolbar2Tk(canvas, root, pack_toolbar=False)
toolbar.update()

canvas.mpl_connect(
    "key_press_event", lambda event: print(f"you pressed {event.key}"))
canvas.mpl_connect("key_press_event", key_press_handler)

# 新增暂停状态变量
is_paused = False

def toggle_pause():
    global is_paused, pause_btn
    if is_paused:
        # 恢复动画
        anim.resume()
        pause_btn.config(text="Pause")
    else:
        # 暂停动画
        anim.pause()
        pause_btn.config(text="Resume")
    is_paused = not is_paused

# 新增Pause按钮
pause_btn = tkinter.Button(master=root, text="Pause", command=toggle_pause)
pause_btn.pack(side=tkinter.BOTTOM)

button = tkinter.Button(master=root, text="Quit", command=root.quit)
button.pack(side=tkinter.BOTTOM)

toolbar.pack(side=tkinter.BOTTOM, fill=tkinter.X)
canvas.get_tk_widget().pack(side=tkinter.TOP, fill=tkinter.BOTH, expand=1)

def init():
    line.set_data([], [])
    return line,

def animate(i):
    x = np.linspace(0, 2, 1000)
    y = np.sin(2 * np.pi * (x - 0.01 * i))
    line.set_data(x, y)
    return line,

anim = animation.FuncAnimation(fig, animate, init_func=init,frames=200, interval=20, blit=True)

tkinter.mainloop()

运行代码后,点击Pause按钮即可暂停动画,按钮文本会变为Resume,再次点击即可恢复动画播放。

内容的提问来源于stack exchange,提问作者solo

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 17:45:05