# ColorSpiralInput.py
import turtle
t = turtle.Pen()
turtle.bgcolor('black')
# Set up a list of any 8 valid Python color names
colors = ['red', 'yellow', 'blue', 'green', 'orange', 'purple', 'white', 'gray']
# Ask the user for the number of sides, between 1 and 8, with a default of 4
sides = int(turtle.numinput('Number of sides', 'How many sides do you want (1-8)?',
4, 1, 8))
# Draw a colorful spiral with the user-specified number of sides
for x in range(360):
t.pencolor(colors[x%sides]) # Only use the right number of colors
t.forward(x*3/sides+x) # Change the size to match number of sides
t.left(360/sides+1) # Turn 360 degrees / number of sides, plus 1
t.width(x*sides/200) # Make the pen larger as it goes outward
When I run this code in sublime text 3, the output window immediately closes when the program has run. I cannot have a look at the result and then close the window manually.
I have reviewed my code but I have no explanation for that. I have written other scripts but I have not encountered the same behaviour of the editor.
Could it be that I have to change some settings?
For generic Python turtle running in the console, the final statement executed is usually mainloop()
or one of its variants, done()
or exitonclick()
. This turns control over to the underlying tkinter event handler.
However, when running under an IDE like IDLE, PyCharm, SublimeText, etc. the rule changes and is not consistent. Some need the final mainloop()
, some don't want it, some turn it into a no-op. Here's how I would write your program to run under the console:
# ColorSpiralInputurtle.py
from turtle import Screen, Turtle
# Set up a list of any 8 valid Python color names
COLORS = ['red', 'yellow', 'blue', 'green', 'orange', 'purple', 'white', 'gray']
screen = Screen()
screen.bgcolor('black')
# Ask the user for the number of sides, between 1 and 8, with a default of 4
sides = int(screen.numinput('Number of sides', 'How many sides do you want (1-8)?', 4, 1, 8))
turtle = Turtle()
turtle.speed('fastest') # because I have no patience
# Draw a colorful spiral with the user-specified number of sides
for x in range(360):
turtle.pencolor(COLORS[x % sides]) # Only use the right number of colors
turtle.forward(x * 3 / sides + x) # Change the size to match number of sides
turtle.left(360 / sides + 1) # Turn 360 degrees / number of sides, plus 1
turtle.width(x * sides / 200) # Make the pen larger as it goes outward
screen.exitonclick()
If your IDE rejects mainloop()
, done()
and/or exitonclick()
, you can always use tell your user to type when they're done looking at your output, and put a final input()
call in your code.