【问题标题】:Matplotlib Usage in Standalone (Exe) Python FileMatplotlib 在独立(Exe)Python 文件中的使用
【发布时间】:2020-12-07 17:57:26
【问题描述】:

我无法从我的 Python 脚本创建一个有效的 exe 文件。我能够将其范围缩小到 matplotlib 的使用范围,但我不知道如何解决。

我创建 exe 文件,使用pyinstaller --onefile myScript.py 命令。 exe 是使用一些“忽略”的导入创建的,例如:

信息:Matplotlib 后端“GTK3Agg”:忽略 后端 Gtk3Agg 需要 cairo

当我运行 exe 时,会出现一个命令窗口,给出一个错误,然后自行终止:

错误:运行时错误找不到 matplotlib 数据文件

如果我从 Python 终端运行代码,一切正常。 如果我删除 matplotlib 和图形相关的线,exe 会正确创建。

一些 (pyinstaller and matplotlib - error while executring .exe) 声称解决方案是更新 pyinstaller。我做了,它没有帮助。

有人建议不要使用plt (Python Matplotlib runtime error upon closing the console),但后来我无法使subplot 函数工作。

我觉得这个链接 (http://www.py2exe.org/index.cgi/MatPlotLib) 是相关的,但我不明白我到底需要做什么。我在尝试时遇到了其他错误。

这是我的代码:

import  tkinter           as tk
import  tkinter.ttk       as ttk
import  matplotlib.pyplot as plt

class myApp(tk.Frame):
    def __init__(self, parent, *args, **kwargs):
        tk.Frame.__init__(self, parent, *args, **kwargs)
        self.parent = parent
        myFrame = ttk.LabelFrame(self.parent, text="FRAME", borderwidth=5)
        myFrame.grid(row=0, column=2, padx=5, pady=5, sticky='NS')
        myButton = ttk.Button(myFrame, width=12, text="SHOW GRAPH", command=self.showGraph)    .grid(row=0, column=1, sticky=tk.S)

    def showGraph(self):
        fig, axs = plt.subplots(2, 3)
        plt.show(block=False)


def main(root):
    app = myApp(root)
    root.wm_title("MyApp")
    root.mainloop()

if __name__ == "__main__":
    root = tk.Tk()
    main(root)
else:
    pass 

注意:我在 Windows 10 上运行 Python 3.8.3,pip 版本 20.2.2。

【问题讨论】:

    标签: python matplotlib pyinstaller python-standalone


    【解决方案1】:

    如果您使用 .spec 文件,我必须将其添加到我的文件中以消除该错误:

    from PyInstaller.utils.hooks import exec_statement
    mpl_data_dir = exec_statement("import matplotlib; print(matplotlib._get_data_path())")
    datas=[(mpl_data_dir, 'matplotlib\\mpl-data')]
    

    希望对您有所帮助。

    【讨论】:

    • 感谢您的帮助,罗斯。我不使用规范文件,但我注意到工作目录中有一个。因此,我将您的行粘贴到该文件中,最重要的是然后再试一次。 exe创建现在没有警告,但是当我双击exe文件时,它仍然抱怨找不到matplotlib文件。 exe仍然无法正常工作。我还需要将lib文件复制到同一文件夹吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-09-09
    • 1970-01-01
    • 2017-03-07
    • 2018-04-10
    • 2021-10-31
    • 2013-12-06
    • 1970-01-01
    相关资源
    最近更新 更多