Dear Pyinstaller and 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’
P.S. Importing this “matplotlib.backends.backend_pdf” module in code does not help
Command to compile:
pyInstaller.exe SaveToPdfApp.py --onedir --noconsole --noconfirm --noupx --console
Simple sample code:
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()
--
You received this message because you are subscribed to the Google Groups "PyInstaller" group.
To unsubscribe from this group and stop receiving emails from it, send an email to pyinstaller...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/pyinstaller/5df5f033-dada-4b97-849e-397fce45b6e8n%40googlegroups.com.
Matplotlib’s array of interchangeable backends model is fairly ambiguous to PyInstaller — particularly if you want more than one backend. Telling PyInstaller which backends you want straightens it out.
# In your spec file a = Analysis( ... hooksconfig={ "matplotlib": { "backends": ["TkAgg", "pdf"], } }, ... )That said, just adding a dumb --hiddenimport=matplotlib.backends.backend_pdf to the build command does the trick for me too.