_tkinter.TclError:没有显示名称,也没有$ DISPLAY环境变量

我在服务器中运行一个简单的python脚本:


import matplotlib.pyplot as plt

import numpy as np


x = np.random.randn(60)

y = np.random.randn(60)


plt.scatter(x, y, s=20)


out_png = 'path/to/store/out_file.png'

plt.savefig(out_png, dpi=150)

我尝试python example.py在已安装matplotlib 1.5.1的服务器中使用该命令,但失败并显示以下错误:


Traceback (most recent call last):

  File "example.py", line 7, in <module>

    plt.scatter(x, y, s=20)

  File "/home/USER/.virtualenvs/nnet/lib/python2.7/site-packages/matplotlib/pyplot.py", line 3241, in scatter

    ax = gca()

  File "/home/USER/.virtualenvs/nnet/lib/python2.7/site-packages/matplotlib/pyplot.py", line 928, in gca

    return gcf().gca(**kwargs)

  File "/home/USER/.virtualenvs/nnet/lib/python2.7/site-packages/matplotlib/pyplot.py", line 578, in gcf

    return figure()

  File "/home/USER/.virtualenvs/nnet/lib/python2.7/site-packages/matplotlib/pyplot.py", line 527, in figure

**kwargs)

  File "/home/USER/.virtualenvs/nnet/lib/python2.7/site-packages/matplotlib/backends/backend_tkagg.py", line 84, in new_figure_manager

    return new_figure_manager_given_figure(num, figure)

  File "/home/USER/.virtualenvs/nnet/lib/python2.7/site-packages/matplotlib/backends/backend_tkagg.py", line 92, in new_figure_manager_given_figure

    window = Tk.Tk()

  File "/usr/local/lib/python2.7/lib-tk/Tkinter.py", line 1810, in __init__

    self.tk = _tkinter.create(screenName, baseName, className, interactive, wantobjects, useTk, sync, use)

_tkinter.TclError: no display name and no $DISPLAY environment variable

这是怎么回事


回首忆惘然
浏览 653回答 3
3回答

一只甜甜圈

您可以通过在.py脚本的非常开头添加这两行来解决此问题。import matplotlibmatplotlib.use('Agg')PS:如果在源代码的开头没有添加这两行,则错误仍然存在。

桃花长相依

为了加总答案,我在所需脚本的开头使用了它。因此它可以在不同的环境下平稳运行。import osimport matplotlib as mplif os.environ.get('DISPLAY','') == '':&nbsp; &nbsp; print('no display found. Using non-interactive Agg backend')&nbsp; &nbsp; mpl.use('Agg')import matplotlib.pyplot as plt因为我不希望它总是使用'Agg'后端,所以仅当它通过Travis CI时才使用。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python