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

Matplotlib中fig.show()仅显示1秒即关闭,添加block参数报错如何解决?

Matplotlib绘图窗口秒关及block参数报错解决办法

问题原因

  1. 绘图窗口秒关:脚本执行完成后主线程直接退出,导致Matplotlib的绘图窗口被自动关闭。
  2. block=True报错:Figure.show()方法(即你使用的fig_Ah.show())本身不支持block参数,该参数属于全局的plt.show()函数,而非Figure实例的方法。

解决办法

方法1:使用全局plt.show(block=True)替换fig_Ah.show()

将代码中的fig_Ah.show()替换为plt.show(block=True),block=True会让脚本阻塞,直到你手动关闭绘图窗口,避免窗口秒关。

修改后的完整代码:

def Ah_cha_and_dcha():
    fig_Ah, ax1 = plt.subplots(nrows=1, ncols=1)
    ax1.plot(time, Ah_Charge, label='Ah Charge')
    ax1.plot(time, Ah_Disharge, label='Ah Discharge')
    ax1.set_xlabel('Test Time [s]')
    ax1.set_ylabel('Ah')
    ax1.set_ylim(-1,110)
    ax1.legend()
    fig_Ah.savefig("Ah.png")
    plt.show(block=True)  # 替换原fig_Ah.show()

方法2:添加手动阻塞代码

如果想保留fig_Ah.show(),可以在其后面添加一行阻塞输入的代码,让脚本等待用户操作后再结束:

def Ah_cha_and_dcha():
    fig_Ah, ax1 = plt.subplots(nrows=1, ncols=1)
    ax1.plot(time, Ah_Charge, label='Ah Charge')
    ax1.plot(time, Ah_Disharge, label='Ah Discharge')
    ax1.set_xlabel('Test Time [s]')
    ax1.set_ylabel('Ah')
    ax1.set_ylim(-1,110)
    ax1.legend()
    fig_Ah.savefig("Ah.png")
    fig_Ah.show()
    input("Press Enter to close the window...")  # 等待用户输入再结束脚本

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 12:32:12