padawan
padawan

Reputation: 1315

Is it possible to use turtle without the graphics window?

I am working on a simulation which requires geometric computations. turtle library makes my life much easier because of the convenient functions that I can use such as towards(), setheading(), goto(), etc.

However, I do not need to see the drawing. Is there a way to turn off the graphics window? I only want to output the results of the simulations in a text file.

Upvotes: 4

Views: 909

Answers (2)

Penguin Bros
Penguin Bros

Reputation: 58

Unfortunately, through my own experience and reading those of others, there isn't a simple in-built method in the Turtle module to hide the window or prevent the window from being instantiated.

However, there is a way to hide it by directly using tkinter, the underlying package that creates the graphics window for turtle, and the RawTurtle class (credit to this answer).

  1. Instantiate a Tk object to serve as the main window
  2. Call the withdraw() method (alias for the wm_withdraw() method) on it (this hides the window)
  3. Instantiate a tkinter.Canvas instance using the Tk object we created as its master window
  4. Pass the Canvas instance to a RawTurtle instance.
import tkinter
import turtle

main = tkinter.Tk()
main.withdraw()
canv = tkinter.Canvas(master = main)
turt = turtle.RawTurtle(canv)

# <insert rest of code here utilizing the RawTurtle instance>

RawTurtle's constructor takes the Canvas instance as the environment in which the turtle draws. By doing this, we hide the window that is typically automatically constructed and passed to the Turtle object (the Turtle class that is typically used is actually a subclass of the RawTurtle class that doesn't require an inputted Canvas instance to be constructed)

Something to remember with this solution is that the graphics system is still initiated despite the window being hidden; if you wanted to eliminate the initialization of the graphics system and window entirely, you would have to reimplement TurtleScreenBase to eliminate any calls to the Tk instance used by the turtle. At that point, I would recommend looking at extending or reimplementing many of the turtle methods/functions to better fit the needs of your project.

Hope this helped!

Upvotes: 3

FractalLotus
FractalLotus

Reputation: 368

I don't know of a way to do this with Python Turtle but NetLogo can be run headless. Since it can be run from the command line it could be launched from a Python script.

From the NetLogo documentation:

NetLogo is a programmable modeling environment for simulating natural and social phenomena. [...] Headless mode allows doing batch runs from the command line [...] Command line operation is also supported.

Upvotes: -1

Related Questions