首页 > 解决方案 > 将另一个函数中的 matplotlib 图保存为图像但不显示该图

问题描述

我正在用 Python + Tkinter 编写一个学校项目,我正在尝试制作一个按钮,单击该按钮会保存在其他函数(createPlot())中创建的图,但不显示实际图。我想避免代码重复,因此,我不想只是从 createPlot() 函数中复制代码并更改最后一行。你知道怎么做吗?我会很感激任何建议。这是代码的主要部分:

def createPlot():
    try:
        plt.style.use('Solarize_Light2')
        plt.plot(analyzeTotalNumOfInfected(),color='y', label='Some Label')
        plt.plot(analyzeNumOfTestsPerDay(),color='r', linestyle='--', label='another Label')
        plt.legend()
        plt.tight_layout
        plt.grid(True)
        fig = plt.gcf()
        fig.canvas.set_window_title('Window title...')
        plt.title('Plot title')
        plt.ylabel('y axis')
        plt.xlabel('x axis')
        plt.show()
    except FileNotFoundError as e:
        messagebox.showerror("Error!", "Lorem Ipsum")

    except Exception as e:
        messagebox.showerror("Error2!", "Lorem Ipsum2")

def savePlot():
    fig = createPlot()
    fig.savefig(os.path.join(sFolder_path,"image.png"))

标签: pythonmatplotlibtkinter

解决方案


你可以修改你的 savePlot() 方法,这样图像名称就不会被覆盖:

from datetime import datetime

def savePlot():
    time = datetime.now().ctime().replace(" ", "")
    fig = createPlot()
    fig.savefig(os.path.join(sFolder_path, f"image@{time}.png"))

推荐阅读