python - 将另一个函数中的 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"))
解决方案
你可以修改你的 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"))
推荐阅读
- c# - c# DataAnnotations 如何验证 IList 中的电话号码
? - swift - 输入我的卡详细信息后,我无法获得 Stripe 付款 ID
- c++ - C++ 是否有库社区?
- ios - 如何解决“请求的应用程序不可用或不存在”。在试飞中
- excel - 正确总结双日班的日历天数 - Excel
- ssl - GeoServer 和 MariaDB 之间的连接问题
- json - 部署 ARM 模板时要更改的 JSON 参数
- recaptcha - 为什么 reCAPTCHA 允许垃圾邮件?
- python - 优先加入 PySpark 数据帧
- php - wkhtml用utf-8泰米尔语导出pdf