0

This is my error log:

% docker run --env=DISPLAY -t my-docker1:latest               
Traceback (most recent call last):
  File "/app/main.py", line 8, in <module>
    matplotlib.use('TkAgg')
  File "/usr/local/lib/python3.9/site-packages/matplotlib/__init__.py", line 1144, in use
    plt.switch_backend(name)
  File "/usr/local/lib/python3.9/site-packages/matplotlib/pyplot.py", line 296, in switch_backend
    raise ImportError(
ImportError: Cannot load backend 'TkAgg' which requires the 'tk' interactive framework, as 'headless' is currently running

Also sharing my code scripts so it can be repeated

main.py

import matplotlib
import matplotlib.pyplot as plt

import os

print(os.getenv('DISPLAY'))
import numpy as np

matplotlib.use('TkAgg')
plt.switch_backend('tkagg')
plt.imshow(np.random.randn(4, 5))

requirements.txt


cycler==0.11.0
fonttools==4.34.4
kiwisolver==1.4.3
lxml==4.9.1
matplotlib==3.5.2
numpy==1.23.1
packaging==21.3
pyparsing==3.0.9
six==1.16.0
soupsieve==2.3.2.post1
webencodings==0.5.1
lxml==4.9.1

main.py

FROM python:3.9.13-slim-buster
WORKDIR /app

ADD main.py .
ADD requirements.txt .

RUN apt-get update
RUN apt-get install ffmpeg libsm6 libxext6  -y
RUN apt-get install python3-tk -y

RUN apt-get install libx11-dev -y
RUN apt-get install tk -y
RUN apt-get install python3-matplotlib -y

# RUN yum install python3-tkinter -y
# RUN pip3 install matplotlib


RUN pip3 install -r requirements.txt
RUN pip3 --no-cache-dir install -U --force-reinstall matplotlib

RUN export DISPLAY=:0
RUN export MPLBACKEND=TKAgg
RUN ls

ENTRYPOINT [ "python", "main.py" ]

I've read tons of similar questions(like this one and tried them all too as you can see in my solution, but none worked, unfortunately.

Any inputs or even suggestions to alternate backends(I tried PyQt5, but that too didn't work)/alternate libraries similar to matplotlib would be great. Thanks!

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
Suraj
  • 2,253
  • 3
  • 17
  • 48
  • 1
    Docker doesn't have a GUI environment. You'd have to use X11 forwarding. Maybe you could use Jupyter, then display plots within that? Otherwise, mount a volume, and save plots to disk – OneCricketeer Jul 12 '22 at 19:12
  • I didn't know that. Thanks for the reply @OneCricketeer, will look into X11 forwarding. – Suraj Jul 12 '22 at 19:48
  • Have you fixed this issue? I've roll back matplotlib to 3.2.1 and it gives me ```_tkinter.TclError: couldn't connect to display "localhost:14.0"``` – K. Zhu Aug 14 '22 at 06:37
  • Nope, I did not solve this @K.Zhu, I ended up using bind mounts and saving images on my disk although that's not what I needed precisely. You could try using Flask and displaying images on the browser, although that'd take more development work. – Suraj Aug 14 '22 at 06:40

0 Answers0