9

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
Gino Mempin
  • 25,369
  • 29
  • 96
  • 135
user2472030
  • 111
  • 1
  • 1
  • 4

2 Answers2

14

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)
MGLondon
  • 1,557
  • 15
  • 18
12

The problem is the tkinter that you are trying to use.

Tk will normally create GUI (like a new window) for your interface. But Colab is run on the web server in the cloud. It can't open a window on your machine. You can only interact with it through notebook interface.

You need to limit the interaction not to use GUI. Or change them to web-based through notebook. What kind of program are you trying to run?

korakot
  • 37,818
  • 16
  • 123
  • 144
  • If you only need matplotlib to plot some graphs. Just remove those tkinter & python3-tk lines. This should solve your problem. – korakot Mar 26 '18 at 09:01
  • In my application, the matplotlib plot window is controlled by a gui that has tkinter buttons and entry fields. So I would like to have both matplotlib and tkinter. – user2472030 Mar 26 '18 at 23:15
  • 1
    Then, you cannot run it in Colab without modification. Colab also support some form entries and GUI form. But you need to modify the code, and there’s no tutorial on Colab GUI yet, because it’s very new. – korakot Mar 27 '18 at 00:40