本文介绍了_tkinter.TclError:没有显示名称,也没有$ DISPLAY环境变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am running a simple python script in the server:

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,但失败并显示以下错误:

I try to use the command python example.py in this server which has matplotlib 1.5.1 installed it fails with the error:

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后端.

Matplotlib chooses Xwindows backend by default.You need to set matplotlib to not use the Xwindows backend.

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

Add this code to the start of your script (before importing pyplot) and try again:

import matplotlib
matplotlib.use('Agg')

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

Or add to .config/matplotlib/matplotlibrc line backend: Agg to use non-interactive backend.

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

或者在连接到服务器时,使用ssh -X remoteMachine命令使用Xwindows.

Or when connect to server use ssh -X remoteMachine command to use Xwindows.

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

Also you may try to export display: export DISPLAY=mymachine.com:0.0.

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

这篇关于_tkinter.TclError:没有显示名称,也没有$ DISPLAY环境变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 08:43