【问题标题】:_tkinter.TclError: no display name and no $DISPLAY environment variable_tkinter.TclError: 没有显示名称和 $DISPLAY 环境变量
【发布时间】:2016-10-02 22:11:22
【问题描述】:

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

这里发生了什么?

【问题讨论】:

  • 你是通过 ssh 运行的吗?
  • ...没有-X?
  • 如果你在 Jupyter notebook 上运行它,在 notebook %matplotlib inline运行这个命令
  • 如果你通过putty从Win机器连接到远程服务器,你必须安装Xming来转发X11。

标签: python matplotlib tkinter


【解决方案1】:

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

【讨论】:

  • 'ssh -X remoteMachine' 解决了我的问题。谢谢!
  • “Agg”到底是什么?
  • AGG是Anti-grain geometry engine的缩写。
  • matplotlib.use('Agg') 为我工作 - 在 Docker 映像中运行。
  • 如果你通过putty从Win机器连接到远程服务器,你必须安装Xming来转发X11。
【解决方案2】:

您可以通过在 .py 脚本的 VERY 开头添加这两行来解决此问题。

import matplotlib
matplotlib.use('Agg')

PS:如果源代码最开始没有添加这两行,错误仍然存​​在。

【讨论】:

  • 它应该在代码的最开始。这很重要。
  • 这在 docker 上运行 matplotlib 时有效(没有附加显示),但它实际上做了什么?
  • 当我只是在我的 vm 上运行 python 控制台时,这对我有用,但是当作为正在运行的应用程序的一部分时,完全相同的代码在同一个 vm 上失败并出现完全相同的错误。
  • 但是在配置文件中将后端从 TkAgg 更改为 Agg 就成功了。
【解决方案3】:

为了总结答案,我在所需脚本的开头使用了它。所以在不同的环境下都能流畅运行。

import os
import matplotlib as mpl
if os.environ.get('DISPLAY','') == '':
    print('no display found. Using non-interactive Agg backend')
    mpl.use('Agg')
import matplotlib.pyplot as plt

因为我不希望它总是使用'Agg' 后端,只有当它通过 Travis CI 时。

【讨论】:

  • 这个解决方案的附加价值是成为对个人配置影响最小的解决方案。它应该更高。
【解决方案4】:

我在 Raspberry Pi 上远程运行一个简单的 tkinter 应用程序时遇到了同样的问题。就我而言,我确实想在 pi 显示器上显示 tkinter GUI,但我希望能够从我的主机通过 SSH 执行它。我也没有使用 matplotlib,所以这不是我的问题的原因。我可以通过设置 DISPLAY 环境变量来解决这个问题,正如错误所暗示的那样:

export DISPLAY=:0.0

可以在此处找到有关显示环境变量的作用以及语法为何如此奇怪的很好解释:https://askubuntu.com/questions/432255/what-is-display-environment-variable

【讨论】:

  • 我正在尝试使用运行在 ssh 上的 python 和 matplotlib.pyplot 保存绘图...这样做让我:_tkinter.TclError: could't connect to display ":0.0"
【解决方案5】:

另一种解决方案是安装 Xvfb,并将您的显示导出到它。 即:

disp=:8
screen=0
geom=640x480x24
exec Xvfb $disp -screen $screen $geom 2>/tmp/Xvfb.log &

然后

$ export DISPLAY=:8

$ ./example.py

【讨论】:

    【解决方案6】:

    为了在远程计算机的窗口上查看图像、绘图和任何显示的内容,您需要像这样连接到它:

    ssh -X user@hostname
    

    这样您就可以访问 X 服务器。 X 服务器是 X 窗口系统中的一个程序,它在本地机器(即用户直接使用的计算机)上运行并处理对这些计算机上的图形卡、显示屏和输入设备(通常是键盘和鼠标)的所有访问.

    更多信息here

    【讨论】:

      【解决方案7】:

      我在 Colab 上遇到过这个问题,下面的代码行解决了这个问题。 把它放在笔记本的开头。 Reference

      ### CREATE VIRTUAL DISPLAY ###
      !apt-get install -y xvfb # Install X Virtual Frame Buffer
      import os
      os.system('Xvfb :1 -screen 0 1600x1200x16  &')    # create virtual display with size 1600x1200 and 16 bit color. Color can be changed to 24 or 8
      os.environ['DISPLAY']=':1.0'    # tell X clients to use our virtual DISPLAY :1.0.
      
      %matplotlib inline
      
      ### INSTALL GHOSTSCRIPT (Required to display NLTK trees) ###
      !apt install ghostscript python3-tk
      

      【讨论】:

        【解决方案8】:

        我在使用Xshell连接Linux服务器时也遇到了这个问题。

        找方法后,我找到了Xming + Xshell,用matplotlib解决了image imshow问题。

        如果以上方案都不能解决您的问题,请在您使用Xshell的情况下尝试下载Xming。然后在Xshell中设置属性,SSH->tunnel->X11transfer->选择X DISPLAY localhost:0.0

        【讨论】:

          【解决方案9】:

          我想在这里添加一个没有人明确说明实施的答案。

          这是一个很好的资源来参考这个失败: https://matplotlib.org/faq/usage_faq.html

          在我的情况下,使用matplotlib.use 不起作用,因为它已经以某种方式设置在其他地方。但是,我能够通过定义环境变量来克服错误:

          export MPLBACKEND=Agg

          这可以解决问题。

          我的错误专门出现在 CircleCI 流程中,这解决了失败的测试。一件奇怪的事情是,我的测试在使用pytest 运行时会通过,但是在使用parallelismcircleci tests split 功能时会失败。然而,声明这个环境变量解决了这个问题。

          【讨论】:

            【解决方案10】:

            尝试使用python 3,所有问题都解决了

            【讨论】:

            【解决方案11】:

            虽然有解决方案use('Agg'),但可能有人有兴趣解决x11。

            假设我们有一个用户 ml,在 ubuntu20 上使用 python3...

            首先,以ml登录,并写一个ml.py

            $ cat ml.py
            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 = 'out_file.png'
            plt.savefig(out_png, dpi=150)
            

            在运行文件之前,我们应该设置 x11,

            
            $ whoami
            ml
            
            $ touch ~/.Xauthority
            
            $ ls .Xauthority
            .Xauthority
            
            # only this one key is needed for X11 over SSH 
            xauth generate :14 . trusted 
            
            $ echo $DISPLAY
            localhost:14.0
            
            $ xauth list
            ml/unix:14  MIT-MAGIC-COOKIE-1  b6a2833785df5e75e2c8bc34045a55a6
            

            运行...

            $ python3 ml.py
            Matplotlib created a temporary config/cache directory at /tmp/matplotlib-rk288ipf because the default path (/home/ml/.config/matplotlib) is not a writable directory; it is highly recommended to set the MPLCONFIGDIR environment variable to a writable directory, in particular to speed up the import of Matplotlib and to better support multiprocessing.
            Matplotlib is building the font cache; this may take a moment.
            qt.qpa.xcb: X server does not support XInput 2
            failed to get the current screen resources
            

            好吧,更新 OpenGL 和 x11-apps,重新运行

            $ python3 ml.py
            Matplotlib created a temporary config/cache directory at /tmp/matplotlib-87at6bw8 because the default path (/home/zzx/.config/matplotlib) is not a writable directory; it is highly recommended to set the MPLCONFIGDIR environment variable to a writable directory, in particular to speed up the import of Matplotlib and to better support multiprocessing.
            qt.qpa.xcb: X server does not support XInput 2
            failed to get the current screen resources
            

            似乎我们无法获取out_file.png,但是...

            $ export QT_DEBUG_PLUGINS=1
            

            然后重新运行文件,我们得到图像,:)

            【讨论】:

              猜你喜欢
              • 2020-10-24
              • 1970-01-01
              • 2014-01-10
              • 1970-01-01
              • 2013-10-24
              • 2015-05-08
              • 2018-09-03
              • 2019-11-03
              • 1970-01-01
              相关资源
              最近更新 更多