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

Matplotlib绘图窗口无法保持最小化,如何修改代码解决?

解决Matplotlib窗口最小化后自动弹回的问题

你的问题根源在于plt.pause(0.0001)——这个函数每次执行时都会强制将绘图窗口置于前台,导致窗口最小化后立刻弹回。替换成手动绘制和刷新事件的方式就能解决这个问题。

修改后的代码如下:

import matplotlib.pyplot as plt
import numpy as np

def on_close(event):
    event.canvas.figure.axes[0].has_been_closed = True
    print('The Figure is Closed!')

fig, ax = plt.subplots(2, 3)
ax[0,0].has_been_closed = False
fig.canvas.mpl_connect('close_event', on_close)
fig.set_size_inches(15, 8) 

while True:
    for i in range(ax.shape[0]):
        for j in range(ax.shape[1]):
            ax[i,j].clear()
    ax[0, 0].plot(range(10), np.random.rand(10,1), 'r') 
    ax[1, 0].plot(np.random.rand(10,1), 'b') 
    ax[0, 1].plot(np.random.rand(10,1), 'g') 
    ax[1, 1].plot(np.random.rand(10,1), 'k')
    ax[0, 2].plot(np.random.rand(10,1), 'g') 
    ax[1, 2].plot(np.random.rand(10,1), 'k') 

    # 替换plt.pause,手动刷新绘图和处理窗口事件
    fig.canvas.draw()
    fig.canvas.flush_events()
    
    if ax[0,0].has_been_closed:
        break

关键修改说明:

  • 移除plt.pause(0.0001),改用fig.canvas.draw()绘制最新图形,fig.canvas.flush_events()处理窗口交互事件(包括最小化、关闭操作)
  • 这种方式不会强制窗口置顶,既能保持仪表盘实时更新,又能让窗口稳定保持最小化状态

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.11 16:32:46