TclError: no display name and no $DISPLAY environment variable in Google Colab

I found it from another post on Reddit that you could create a virtual display. The below actually worked on my Colab notebook.

### 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.

In my specific case, I needed to visualise a NLTK tree so I had to follow the additional steps below.

%matplotlib inline
### INSTALL GHOSTSCRIPT (Required to display NLTK trees) ###
!apt install ghostscript python3-tk
chunked_sentence="(S (NP this tree) (VP (V is) (AdjP pretty)))"
from nltk.tree import Tree
from IPython.display import display
tree = Tree.fromstring(str(chunked_sentence))
display(tree)

Leave a Comment