Python Turtle Graphics Window only Opens Briefly then Closes

Question:

I have recently begun using the turtle module in Python, and I admit, I am a complete novice. I have been having trouble getting the graphics window in which the turtle does its drawing to stay open. Even when I try to run something as simple as this:

import turtle
wn = turtle.Screen()
tur = turtle.Turtle()
tur.forward(50)

all I get is the Python launcher icon to appear on my dock for a split second and close. Any help is appreciated, and I am, by the way, doing this in Aptana Studio 3.

Asked By: Randoms

||

Answers:

Add:

import Tkinter
Tkinter.mainloop()

to the end of your script, and that’ll fix it.

What’s happening is that once you’ve created a screen and drawn to it, there’s nothing to stop Python from immediately exiting. The call to Tkinter.mainloop synchronously processes events from Tkinter (the GUI toolkit on which Python’s turtle library is built) until the screen window is closed.

Answered By: javawizard

Also, you may want to try

turtle.mainloop()

which in my opinion just works slightly better than with Tk.

From the docs for turtle.mainloop():

Starts event loop – calling Tkinter’s mainloop function. Must be the last statement in a turtle graphics program. Must not be used if a script is run from within IDLE in -n mode (No subprocess) – for interactive use of turtle graphics.

turtle.done() is an alias of turtle.mainloop().

Answered By: 5813

Or you can try adding:

wn.exitonclick()

Which will leave the graphics window open until you click on it.

Answered By: SaretMagnoslove

I have the same problem. I can see the Turtle window very briefly, just a short flash, and then it’s gone. To remedy, I just write input() at the end of my code. This will prevent the Turtle window from closing so one can see what is going on.

Also turtle.mainloop() is working for me.

Answered By: jay123

Adding turtle.done() as the last statement in your turtle graphics program will keep the Window open.

Answered By: Ying

When I enter the following code:

import turtle as t
t.fd(100)

The window containing the turtle graphics just appears and closes. But when I enter the following code:

import turtle as t
t.fd(100)
t.mainloop()

The window does not automatically disappear the way it did before.

Hence t.mainloop() or turtle.mainloop() depending on how you import the library, can be used to make the window stay open as long as you want.

Hope this was helpful!

Answered By: Anshika Singh

For all programmers who’s still having the same issue, make sure that you have the latest version of python installed. In case you don’t, download it and try to run your code again.

Answered By: SuperMEgA12