Dear Matplotlib users. Found this problem with my project
Matplotlib and Tkinter based application with export to PDF works great until you compile it to Exe file by PyInstaller. So I made simple app that show the problem:
When execute Exe file and try to export pdf file - program drop this error text to console:
ModuleNotFoundError: No module named ‘matplotlib.backends.backend_pdf’
Importing this “matplotlib.backends.backend_pdf” module in code does not help
#pyInstaller.exe SaveToPdfApp.py --onedir --noconsole --noconfirm --noupx --console
import tkinter as tk
from tkinter import filedialog
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import matplotlib.pyplot as plt
import numpy as np
#from matplotlib.backends.backend_pdf import PdfPages
def save_plot_as_pdf():
file_path = filedialog.asksaveasfilename(defaultextension=".pdf", filetypes=[("PDF files", "*.pdf")])
if file_path:
#with PdfPages(file_path) as pdf:
#pdf.savefig(figure)
figure.savefig(file_path, format="pdf")
print(f"Plot saved as {file_path}")
root = tk.Tk()
root.title("Matplotlib Plot in Tkinter")
x = np.linspace(0, 10, 100)
y = np.sin(x)
figure = plt.Figure(figsize=(6, 4), dpi=100)
ax = figure.add_subplot(111)
ax.plot(x, y, label="Sine wave")
ax.set_title("Simple Sine Wave Plot")
ax.set_xlabel("X-axis")
ax.set_ylabel("Y-axis")
ax.legend()
canvas = FigureCanvasTkAgg(figure, root)
canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=1)
save_button = tk.Button(root, text="Save as PDF", command=save_plot_as_pdf)
save_button.pack(side=tk.BOTTOM)
root.mainloop()