manishsingh373
manishsingh373

Reputation: 11

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?

Upvotes: 1

Views: 24265

Answers (6)

Emmanuel Chukwu
Emmanuel Chukwu

Reputation: 11

from turtle import Turtle, Screen

t = Turtle()
t.shape("turtle")
t.color("red")

def dash_line(number_of_times):
    t.pencolor("black")
    for move in range(number_of_times):
        t.forward(10)
        t.pu()
        t.forward(10)
        t.pd()

dash_line(10)

Upvotes: 0

Sandul Ranmuthu
Sandul Ranmuthu

Reputation: 1

You can use this method to draw a dashed line using a specific distance. By changing the <dis> and <size> values you can set the distance and the dash size.

from turtle import *

###for loop to draw a dotted line###
for i in range(<dis>):
    if int(i/<size>)%2==1:
        pencolor('white')
    else:
        pencolor('black')
    forward(1)
pencolor('black')

Upvotes: 0

Saeed Ismail
Saeed Ismail

Reputation: 1

from turtle import Turtle, Screen

t = Turtle()
t.shape("turtle")
t.color("red")

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

Upvotes: 0

Omotola Ademola
Omotola Ademola

Reputation: 1

from turtle import Turtle, Screen

turtle = Turtle()

for _ in range(50):
    turtle.color("green")
    turtle.forward(10)
    turtle.penup()
    turtle.forward(10)
    turtle.pendown()

screen = Screen()
screen.exitonclick()

Upvotes: 0

Sanka Weerathunga
Sanka Weerathunga

Reputation: 11

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()

Upvotes: 0

coconut
coconut

Reputation: 115

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.

Upvotes: 9

Related Questions