构建成功但代码不起作用,抛出 ImportError

build is successful but code doesn't work, throwing ImportError

我的问题和网上已有的问题没什么区别。让我尝试详细突出显示它。我有 this code to do some plotting by reading a .txt file specified. I was going to build it as usually as I did before. My setup.py is supposed to do the job. The content of setup.py is here

如您所见,我在上述两个文件中都没有与 tkinter 相关的任何包。我在终端中做了 python setup.py build 并且执行得很好。但是不能将我的实际代码与 windows 命令脚本一起使用

build\exe.win-amd64-3.5\draw_precision_recall_curve.exe D:\dataset\Fire_Smoke\Train\filelist.txt 
 pause 

它抛出这个痕迹:

Traceback (most recent call last):
  File "C:\python354\lib\site-packages\cx_Freeze\initscripts\__startup__.py", line 14, in run
    module.run()
  File "C:\python354\lib\site-packages\cx_Freeze\initscripts\Console.py", line 26, in run
    exec(code, m.__dict__)
  File "draw_precision_recall_curve.py", line 3, in <module>
    import matplotlib.pyplot as plt
  File "C:\python354\lib\site-packages\matplotlib\pyplot.py", line 115, in <module>
    _backend_mod, new_figure_manager, draw_if_interactive, _show = pylab_setup()
  File "C:\python354\lib\site-packages\matplotlib\backends\__init__.py", line 62, in pylab_setup
    [backend_name], 0)
  File "C:\python354\lib\site-packages\matplotlib\backends\backend_tkagg.py", line 4, in <module>
    from . import tkagg  # Paint image to Tk photo blitter extension.
  File "C:\python354\lib\site-packages\matplotlib\backends\tkagg.py", line 5, in <module>
    from six.moves import tkinter as Tk
  File "C:\python354\lib\site-packages\six.py", line 92, in __get__
    result = self._resolve()
  File "C:\python354\lib\site-packages\six.py", line 115, in _resolve
    return _import_module(self.mod)
  File "C:\python354\lib\site-packages\six.py", line 82, in _import_module
    __import__(name)
ImportError: No module named 'tkinter'

查看相关帖子,我无法解决这个问题。 感谢任何帮助。

您可能没有使用 tkinter,但您 使用 matplotlib,它使用 tkinter

事实上,matplotlib 给你 a choice of backends。但是 IIRC,如果您尚未安装可选的 Win32 本机后端,则默认值为 tkinter(或者可能 TkAgg,它使用 tkinter) Windows,并且始终打开非Mac Unix.

所以:

  • 如果您仅以非图形方式使用 matplotlib——例如,生成要保存的文件——明确指定非交互式后端。
  • 如果您使用它来显示图表,您需要在您的应用中捆绑 tkinter,或者选择不同的交互式后端并在您的应用中捆绑 that应用

例如,假设您只想生成一堆图形作为 PNG 文件。您可以使用 AGG 非交互式后端,而不是通过默认的 TkAgg 后端执行此操作,如下所示:

import matplotlib
matplotlib.use('AGG')
import matplotlib.pyplot as plt