python - _tkinter.TclError : no display name and n

我正在服务器中运行一个简单的 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)

我尝试在安装了 matplotlib 1.5.1 的服务器中使用命令 python example.py 失败并出现错误:

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

这里发生了什么?

最佳答案

Matplotlib 默认选择 Xwindows 后端。 您需要将 matplotlib 设置为不使用 Xwindows 后端。

将此代码添加到脚本的开头(在导入 pyplot 之前)并重试:

import matplotlib
matplotlib.use('Agg')

或添加到 .config/matplotlib/matplotlibrcbackend: Agg使用非交互式后端。

echo "backend: Agg" > ~/.config/matplotlib/matplotlibrc

或者在连接服务器时使用ssh -X remoteMachine命令来使用Xwindows。

您也可以尝试导出显示:export DISPLAY=mymachine.com:0.0

更多信息:https://matplotlib.org/faq/howto_faq.html#matplotlib-in-a-web-application-server

关于python - _tkinter.TclError : no display name and no $DISPLAY environment variable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37604289/

相关文章:

python - 重命名 virtualenv 文件夹而不破坏它

linux - Bash 脚本在空行上打印 "Command Not Found"

linux - 如何在 Linux shell 脚本中插入新行?

linux - 如何将当前正在运行的 linux 进程置于后台?

python - 将列表列表获取到 pandas DataFrame

python - Django 动态模型字段

linux - 将 awk 与列值条件一起使用

python - Windows 上的错误 "Import Error: No module nam

windows - 为什么在 Windows 上创建新进程比在 Linux 上更昂贵?

linux - 64 位 Linux 机器上的 Android SDK