Kabdmenrs Kabdmenrs - 26 days ago 6
Python Question

My define statement will only run once

After my code prints one dot on the screen it doesn't run again. This is what it tells me in the terminal after I close the turtle screen:

Traceback (most recent call last):
File "/Users/Benjamin/Desktop/Space Digital Scene.py", line 33, in <module>
star(size, x, y, color)
File "/Users/Benjamin/Desktop/Space Digital Scene.py", line 12, in star
drawer.begin_fill()
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/turtle.py", line 3322, in begin_fill
self._fillitem = self.screen._createpoly()
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/turtle.py", line 497, in _createpoly
return self.cv.create_polygon((0, 0, 0, 0, 0, 0), fill="", outline="")
File "<string>", line 1, in create_polygon
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/tkinter/__init__.py", line 2492, in create_polygon
return self._create('polygon', args, kw)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/tkinter/__init__.py", line 2474, in _create
*(args + self._options(cnf, kw))))
_tkinter.TclError: invalid command name ".!canvas"


My code is

import turtle
import random

def star(size, X, Y, color):
drawer.goto(X, Y)
drawer.color(color)
drawer.begin_fill()
drawer.circle(size)
drawer.end_fill()

hex = ["blue","red","yellow","white"]

screen = turtle.Screen()
turtle.bgcolor("black")
drawer = turtle.Turtle()
drawer.speed("fastest")

x = random.randint(-300,301)
y = random.randint(-300,301)
color = random.choice(hex)
size = random.randint(1,6)

a = 1
b = 100

while True:
if a <= b:
star(size, x, y, color)
drawer.hideturtle()
a + 1
continue
else:
break

screen.mainloop()

Answer Source

You have to assign the new a or use a += 1 and also move some lines inside the while loop to execute them each time:

while True:
    if a <= b:
        x = random.randint(-300, 301)
        y = random.randint(-300, 301)
        star(size, x, y, color)
        drawer.hideturtle()
        a += 1

        continue
    else:
        break

screen.mainloop()