Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Draw dashed line using turtle graphics

from turtle import Turtle, Screen
tt_turtle_obj = Turtle()

for _ in range(15):
    tt_turtle_obj.forward(10)
    tt_turtle_obj.color("white")
    tt_turtle_obj.forward(10)
    tt_turtle_obj.color("black")

screen = Screen()
screen.exitonclick()

I used this code to do the same. Is there any other way?

like image 500
manishsingh373 Avatar asked Sep 10 '26 18:09

manishsingh373


2 Answers

You can use the turtle.penup() and turtle.pendown() methods, to control when the turtle will draw on the canvas and when it won't. Here is the code:

from turtle import Turtle, Screen
tt_turtle_obj = Turtle()

for _ in range(15):
    tt_turtle_obj.forward(10)
    tt_turtle_obj.penup()
    tt_turtle_obj.forward(10)
    tt_turtle_obj.pendown()

screen = Screen()
screen.exitonclick()

This way, you can draw a dashed line over any background and the code can be reused in different scenarios. In the end, both codes do the same thing.

like image 74
coconut Avatar answered Sep 13 '26 07:09

coconut


Instead of turtle.color() try turtle.pencolor() to changes the colour in a line.

from turtle import Turtle, Screen
tt_turtle_obj = Turtle()

for _ in range(15):
  tt_turtle_obj.forward(10)
  tt_turtle_obj.pencolor("black")
  tt_turtle_obj.forward(10)
  tt_turtle_obj.pencolor("white")

screen = Screen()
screen.exitonclick()
like image 37
Sanka Weerathunga Avatar answered Sep 13 '26 08:09

Sanka Weerathunga



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!