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

Matplotlib循环更新图表后保持窗口打开且脚本继续执行的实现

问题:Matplotlib循环绘图后保持窗口打开且脚本继续执行

需求:实现一个在循环中动态更新的Matplotlib图表,要求循环结束后图表窗口保持打开状态,同时脚本继续执行后续代码(比如打印指定内容)。

原示例代码:

import tkinter
import matplotlib as mpl
mpl.use('TKAgg', force=True)
import matplotlib.pyplot as plt
import random

def main():
  showFigure()
  print("This is printed before the figure is closed.")

def showFigure():
  x, y = [], []
  plt.ion()
  fig = plt.figure()

  for i in range(0, 100):
    x.append(i)
    y.append(random.randint(0, 10))
    plt.plot(x, y, 'r-')

    fig.canvas.draw()
    fig.canvas.flush_events()
  

if __name__ == '__main__':
  main()

尝试过的方法及问题:

  • 添加 plt.show(block=True):窗口保持打开,但必须关闭窗口后脚本才会继续执行,不符合需求;
  • 添加 plt.show(block=False) 或 plt.show():循环结束后窗口自动关闭,也不符合需求。

解决方案

修改后的代码:

import tkinter
import matplotlib as mpl
mpl.use('TKAgg', force=True)
import matplotlib.pyplot as plt
import random

def main():
  showFigure()
  print("This is printed before the figure is closed.")

def showFigure():
  x, y = [], []
  plt.ion()
  fig = plt.figure()

  for i in range(0, 100):
    x.append(i)
    y.append(random.randint(0, 10))
    plt.plot(x, y, 'r-')

    fig.canvas.draw()
    fig.canvas.flush_events()
  
  # 关键修改:维持窗口事件循环但不阻塞主线程
  def maintain_window():
      fig.canvas.flush_events()
      # 每隔100毫秒刷新一次事件循环
      fig.canvas.after(100, maintain_window)
  
  # 启动后台事件循环维护
  maintain_window()

if __name__ == '__main__':
  main()

原理说明

  1. 利用TKAgg后端基于tkinter的特性,通过fig.canvas.after()方法,每隔固定时间调用一次事件刷新,让图表窗口保持响应状态;
  2. 该方式不会阻塞主线程,所以showFigure()执行完毕后,主线程会立刻继续执行print()语句;
  3. 窗口会一直保持打开,直到手动关闭,关闭后后台的after循环也会自动终止。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 12:43:27