Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using turtle graphics in Google colab

I am working with a student that uses Google colab. I tried introducing her to turtle graphics. We got this error: TclError: no display name and no $DISPLAY environment variable.

When I try to look up the error all the solutions are very specific to matplotlib. That worked for my student without making any adjustment. I am looking for a solution for this that works more generally or at least works with turtle and tkinter.

The student is using a Chrome book. Google colab is what she uses at school, solving the problem in that environment would be best if possible. Did try to create a Turtle object, but this produced the same error.

I did a search on the error all the post I could find talked bout this problem with matplotlib. The solution in that case was to override what I think is a rendering option by invoking .use('Agg'). I did not see an obvious equivalent for turtle.

I also tried using matplotlib, to see if we got the error that I saw in the postings. We tried a simple matplotlib example and it worked without any changes. The graph output appeared as expected.

import turtle
turtle.forward(100)

I expect the turtle graphics to be drawn in the results. What I actually got were these errors:

---------------------------------------------------------------------------
TclError                                  Traceback (most recent call last)
<ipython-input-7-585bbd158605> in <module>()
----> 1 turtle.forward(100)

5 frames
/usr/lib/python3.6/tkinter/__init__.py in __init__(self, screenName, baseName, className, useTk, sync, use)
   2021                 baseName = baseName + ext
   2022         interactive = 0
-> 2023         self.tk = _tkinter.create(screenName, baseName, className, interactive, wantobjects, useTk, sync, use)
   2024         if useTk:
   2025             self._loadtk()

TclError: no display name and no $DISPLAY environment variable
like image 801
James Grimaldi Avatar asked Jun 05 '26 23:06

James Grimaldi


1 Answers

Create an empty code cell, type the following pip command and run it:

!pip3 install ColabTurtle

I recommend you use your turtle like this (in a separate code piece):

import ColabTurtle.Turtle as lia
lia.initializeTurtle(initial_speed=5) 
lia.color('blue')
lia.forward(100)
lia.right(45)
lia.color('red')
lia.forward(50)

You may in fact use direct calls (skip all the lia object ref), but it's not a good idea IMHO since you want your students to get used to using instances. This simplified (less recommended way) would look like this:

import ColabTurtle
forward(100)
right(90)
forward(100)

You are not habituating students to using objects and they cannot see the tool tips (e.g. available methods and properties of the object).

like image 58
Guy Avatar answered Jun 07 '26 13:06

Guy