Home  >  Article  >  Backend Development  >  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?

Susan Sarandon
Susan SarandonOriginal
2024-10-23 00:14:03542browse

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:
<code class="python">import matplotlib
matplotlib.use('Agg')</code>
  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.

The above is the detailed content of How to Solve the \"_tkinter.TclError: no display name and no $DISPLAY environment variable\" Issue for Python Scripts Using Matplotlib on a Server?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn