-2

I want to define a function that draws a shape using turtle graphics. I want the function to be able to clear the turtle graphics window once it is called again. Is there a way to do this or a way that I can close the turtle window once it's done and you press a certain key?

This is the function in question:

import turtle
import math
turtle
def draw(b, d, w, h):
    bDraw = b*10
    dDraw = d*10
    wDraw = w*10
    hDraw = h*10
    bdAngle = abs(math.atan(dDraw/bDraw)*180/math.pi)
    draw = turtle.Turtle()
    draw
    draw.right(90)
    draw.forward(hDraw)
    draw.left(90)
    draw.forward(wDraw)
    draw.left(90)
    draw.forward(hDraw)
    draw.right(90)
    draw.forward(bDraw)
    draw.left(180-bdAngle)
    draw.forward(math.sqrt(dDraw**2 + bDraw**2))
    draw.left(bdAngle)
    draw.forward(wDraw)
    draw.left(90-(180-bdAngle-90))
    draw.forward(math.sqrt(dDraw**2 + bDraw**2))
    draw.left(180-bdAngle)
    draw.forward(bDraw+wDraw)
ggorlen
  • 44,755
  • 7
  • 76
  • 106
  • 1
    use the `clear()` function? – Julien Aug 31 '22 at 01:09
  • 1
    Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking. – Community Aug 31 '22 at 01:13
  • Does this answer your question? [Python: How to reset the turtle graphics window](https://stackoverflow.com/questions/34033701/python-how-to-reset-the-turtle-graphics-window) – ggorlen Aug 31 '22 at 15:46

1 Answers1

0

You have created an instance of turtle each time you called the function draw(b, d, w, h).

When initiating a new drawing session, if those turtle instances are no longer needed, call turtle.clearscreen() to delete all previous drawings and those turtle instances used to craft the drawings.

def draw(b, d, w, h):
    turtle.clearscreen()
    bDraw = b*10
    # your codes proceed

If you'd like to keep those turtle instances for later use, call turtle.resetscreen() instead:

def draw(b, d, w, h):
    turtle.resetscreen()
    bDraw = b*10
    # your codes proceed
zhugen
  • 240
  • 3
  • 11