Search This Blog

How to draw a dashed line in python?

 



In python, to draw a dashed line on a screen, first, turtle module's Turtle class is imported to the program. The turtle is an extensive module that provides turtle graphics primitives, in both object-oriented and procedure-oriented ways. Because it uses tkinter for the underlying graphics, it needs a version of Python installed with Tk support.

It's part of core python libraries so, turtle comes by default with basic python. Just need to import and use.

After importing the turtle, we use the penup and pendown to draw a dashed line. Penup simply means not drawing & Pendown is drawing a line. Like in the code below turtle module's penup & pendown are used to draw a black dashed line.


from turtle import Turtle,Screen #turtle is imported

timmy_the_turtle=Turtle()
timmy_the_turtle.shape('classic')

timmy_the_turtle.color('black')


for i in range(20):
    
    # penup or pu means pick pen up, 
    # so you can move turtle 
      without leaving tracks. 
    # pendown or pd means pick pen down, 
    # so you can move the turtle 
      and leave tracks.
    

    timmy_the_turtle.forward(10)
    # picking up pen
    timmy_the_turtle.penup()
    timmy_the_turtle.forward(10)
    # picking pen down to draw
    timmy_the_turtle.pendown()
    
screen=Screen()
#Allows to exit when user clicks on screen
screen.exitonclick()

No comments:

Post a Comment