Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

This error:

TclError: no display name and no $DISPLAY environment variable

arose when I tried to run a Python 3.6 program inside Google Colab (collaborative Jupyter notebooks). I am running Colab in Chrome on a Windows 10 machine. I've seen this error reported in other threads on Stack Overflow but not in the context of Colab, and previously posted solutions either don't apply or don't seem to work.

My code begins like this:

from matplotlib.pyplot import *
from matplotlib.widgets import *
from math import *
from random import *
from numpy import *
from tkinter import *

Note that to get the import of tkinter to work, I had to issue the following instruction in a different Colab cell:

!apt-get install python3-tk
like image 389
user2472030 Avatar asked Mar 25 '18 16:03

user2472030


People also ask

Can we run tkinter in Google Colab?

You will have to run Python on your desktop or laptop to use tkinter . Additionally, the colab environment is a form of IPython notebook, which is not really a standard Python environment. I would not recommend trying to run tkinter programs from an IPython notebook even if you have IPython running locally.

How do you clear all outputs in Colab?

To clear outputs, go to 'EDIT' and 'clear all outputs'. If you want to reset all packages, data files etc.


1 Answers

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)
like image 55
MGLondon Avatar answered Sep 16 '22 16:09

MGLondon