"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Solve the \"_tkinter.TclError: no display name and no $DISPLAY environment variable\" Issue for Python Scripts Using Matplotlib on a Server?

How to Solve the \"_tkinter.TclError: no display name and no $DISPLAY environment variable\" Issue for Python Scripts Using Matplotlib on a Server?

Published on 2024-11-12
Browse:120

How to Solve the \

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

Issue

Python scripts using Matplotlib fail on a server with the error "no display name and no $DISPLAY environment variable" when generating plots. The issue arises because Matplotlib utilizes the Xwindows backend by default and is incompatible with server environments that lack a graphical user interface (GUI).

Solution

To resolve this issue, set Matplotlib to use a non-interactive backend. There are several methods to achieve this:

  1. Add Code to Script: At the beginning of your script, before importing matplotlib.pyplot, include the following code:
import matplotlib
matplotlib.use('Agg')
  1. Modify Matplotlib Configuration File: In the file .config/matplotlib/matplotlibrc, add the line backend: Agg. This will instruct Matplotlib to use the non-interactive Agg backend.
echo "backend: Agg" > ~/.config/matplotlib/matplotlibrc
  1. Use SSH with X Forwarding: When connecting to the server via SSH, use the -X option to enable Xwindows forwarding. This will allow GUI applications running on the server to interact with the client's GUI environment.
ssh -X remoteMachine.com
  1. Export $DISPLAY Variable: Set the $DISPLAY environment variable to an appropriate value, such as the IP address and display number of the client's machine.
export DISPLAY=mymachine.com:0.0

By implementing one of these solutions, you can configure Matplotlib to operate in a server environment without relying on a GUI.

Release Statement This article is reprinted at: 1729601178 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3