python – _tkinter.TclError: no display name and no $DISPLAY environment variable
python – _tkinter.TclError: no display name and no $DISPLAY environment variable
Matplotlib chooses Xwindows backend by default.
You need to set matplotlib to not use the Xwindows backend.
Add this code to the start of your script (before importing pyplot) and try again:
import matplotlib
matplotlib.use(Agg)
Or add to .config/matplotlib/matplotlibrc
line backend: Agg
to use non-interactive backend.
echo backend: Agg > ~/.config/matplotlib/matplotlibrc
Or when connect to server use ssh -X remoteMachine
command to use Xwindows.
Also you may try to export display: export DISPLAY=mymachine.com:0.0
.
For more info: https://matplotlib.org/faq/howto_faq.html#matplotlib-in-a-web-application-server
You can solve it by adding these two lines in the VERY beginning of your .py script.
import matplotlib
matplotlib.use(Agg)
PS: The error will still exists if these two lines are not added in the very beginning of the source code.
python – _tkinter.TclError: no display name and no $DISPLAY environment variable
To add up on the answer, I used this at the beginning of the needed script. So it runs smoothly on different environments.
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
Because I didnt want it to be alsways using the Agg
backend, only when it would go through Travis CI for example.