0% found this document useful (0 votes)
4 views24 pages

Ad - Python Ch-5 Notes

This document provides an overview of using the Turtle graphics module in Python for creating visual designs and simple GUI applications. It explains key concepts such as the turtle, canvas, and various commands to control the turtle's movement and appearance. Additionally, it covers methods for changing the turtle's pen size, color, speed, and resetting the drawing environment.

Uploaded by

savaliyabhavy422
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views24 pages

Ad - Python Ch-5 Notes

This document provides an overview of using the Turtle graphics module in Python for creating visual designs and simple GUI applications. It explains key concepts such as the turtle, canvas, and various commands to control the turtle's movement and appearance. Additionally, it covers methods for changing the turtle's pen size, color, speed, and resetting the drawing environment.

Uploaded by

savaliyabhavy422
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 24

Advanced Python Programming (UNIT-4) | 4321602

Unit-IV: Graphics with Turtle (Marks-12)

 Graphical User Interfaces (GUI’s) provide a rich environment in which information can be
exchanged between a user and the computer. GUI’s are not limited to simply displaying text and
reading text from the keyboard.
 GUI’s enable users to control the behavior of a program by performing actions such as using the
mouse to drag or click on graphical objects. GUI’s can make using programs much more intuitive
and easier to learn since they provide users with immediate visual feedback that shows the effects of
their actions.
 There are many Python packages that can be used to create graphics and GUI’s.
 Two graphics modules, called turtle and tkinter, come as a part of Python’s standard library. tkinter
is primarily designed for creating GUI’s. In fact, IDLE is built using tkinter.
 However, we will focus on the turtle module that is primarily used as a simple graphics package but
can also be used to create simple GUI’s.

What is Turtle and how is it used to draw objects? SUMMER-2023

What is Python Turtle Graphics?

 Turtle graphics is a beginner-friendly way to learn programming concepts and create visual designs
using a simple graphics library.
 It gets its name from the concept of a "turtle" with a pen that moves on a canvas to draw shapes. The
turtle can be controlled by a set of commands, allowing you to create drawings, patterns, and even
simple games.
 In simple Turtle graphics is a computer programming concept that helps us create drawings and
patterns using a virtual "turtle" that moves on the screen.
 Imagine a canvas or a drawing board, and on this canvas, we have a little "turtle" that we can
control.The turtle has a pen attached to it, and it leaves a trail as it moves around the canvas.
 In turtle graphics, you have a turtle, which is a graphical cursor that can be moved around a drawing
canvas.
 The turtle starts at a specific position, often in the center of the canvas, and has an initial orientation
(usually facing upwards).
 The turtle can be controlled using a set of commands to move, turn, and draw on the canvas

Key Concepts in Turtle Graphics:

Turtle: The "turtle" is a virtual drawing tool that can move around a canvas. Think of it as a small robot
with a pen attached to its tail.

Canvas: The "canvas" is a virtual drawing area where the turtle moves and creates its drawings. It's like a
piece of paper where you can draw.

Commands: You control the turtle using simple commands, such as "move forward," "turn left," "turn
right," "lift the pen," and "lower the pen."

Coordinates: The canvas has a coordinate system, like a grid. The turtle moves around using these
coordinates. The center is (0, 0), and you can move up, down, left, and right from there.

1. Import turtle

 The turtle is built in library so we don't need to install separately. We just need to import the library
into our Python environment.

INFORMATION TECHNOLOGY [Mrs. Aesha K. Virani , Mrs. Hina S. Jayani] 1


Advanced Python Programming (UNIT-4) | 4321602
 The Python turtle library consists of all important methods and functions that we will need to create
our designs and images. Import the turtle library using the following command.

import turtle

2. Import everything from the turtle module

from turtle import *

3. Alias the whole turtle in Python

import turtle as t

 This imports the turtle module using the identifier t.Type this line at the top of your programme.
 The command import turtle as t lets you use functions from the turtle module without having to type
turtle in full time.
 By importing the module this way we access the methods within the module using t.<object> instead
of turtle.<object>.

4. Importing specific member from the module

from turtle import shape

 Only shape is imported into our intial code,rather than importing the whole module.

Example: turtle graphics window

import turtle

# Creating turtle screen

s = turtle.getscreen()

# To stop the screen to display

turtle.mainloop()

O/P:

INFORMATION TECHNOLOGY [Mrs. Aesha K. Virani , Mrs. Hina S. Jayani] 2


Advanced Python Programming (UNIT-4) | 4321602
The screen same as the canvas and turtle acts like a pen. You can move the turtle to design the desired
shape. The turtle has certain changeable features such as color, speed, and size. It can be moved to a specific
direction, and move in that direction unless we tell it otherwise

5.2 Implement graphics using turtle

Explain the various inbuilt methods to change the direction of the turtle. SUMMER-2022

To make use of the turtle methods and functionalities, we need to import turtle.”turtle” comes packed with
the standard Python package and need not be installed externally. The roadmap for executing a turtle
program follows 4 steps:

1. Import the turtle module


2. Create a turtle to control.
3. Draw around using the turtle methods.
4. Run turtle.done().

“Turtle” is a Python feature like a drawing board, which lets us command a turtle to draw all over it! We can
use functions like turtle.forward(…) and turtle.right(…) which can move the turtle around. Commonly used
turtle methods are :

Method Parameter Description

Turtle() None Creates and returns a new turtle object

forward() amount Moves the turtle forward by the specified amount

backward() amount Moves the turtle backward by the specified amount

right() angle Turns the turtle clockwise

left() angle Turns the turtle counterclockwise

penup() None Picks up the turtle’s Pen

pendown() None Puts down the turtle’s Pen

up() None Picks up the turtle’s Pen

down() None Puts down the turtle’s Pen

color() Color name Changes the color of the turtle’s pen

fillcolor() Color name Changes the color of the turtle will use to fill a polygon

heading() None Returns the current heading

INFORMATION TECHNOLOGY [Mrs. Aesha K. Virani , Mrs. Hina S. Jayani] 3


Advanced Python Programming (UNIT-4) | 4321602
Method Parameter Description

position() None Returns the current position

goto() x, y Move the turtle to position x,y

begin_fill() None Remember the starting point for a filled polygon

end_fill() None Close the polygon and fill with the current fill color

dot() None Leave the dot at the current position

stamp() None Leaves an impression of a turtle shape at the current location

shape() shapename Should be ‘arrow’, ‘classic’, ‘turtle’ or ‘circle’

Explain Shape function in Turtle. How many types of shapes are their in turtle? SUMMER-2023,
WINTER-2022

Turtle Shapes

 The turtle.shapes command sets the turtle shape to one of these shapes: “arrow”, “turtle”, “circle”,
“square”, “triangle”, and “classic”.
 Classic shape is the original shape

Import turtle
turtle.shape(“turtle”)
turtle.shape(“arrow”)
turtle.shape(“circle”)

Explain the use of the following turtle function with an appropriate example. (a) turn() (b)
move(). SUMMER-2022
Explain Different ways to move turtle to another position. SUMMER-2023,WINTER-2022

Moving the Turtle

Forward and Backward

 The turtle.forward(distance) or turtle.fw(distance) and turtle.backward(distance) or


turtle.bk(distance) moves the turtle forward or backward by the specified distance, in the direction
the turtle is headed.

Turning

 You can turn the turtle to face a different direction by using either the turtle.right(angle) or
turtle.left(angle) command.

INFORMATION TECHNOLOGY [Mrs. Aesha K. Virani , Mrs. Hina S. Jayani] 4


Advanced Python Programming (UNIT-4) | 4321602
Example:

import turtle as t

t.fd(100)

t.rt(90)

t.fd(100)

t.rt(90)

t.fd(100)

t.rt(90)

t.fd(100)

O/P:

You can also draw a line from your current position to any other arbitrary position on the screen. This is
done with the help of coordinates:

INFORMATION TECHNOLOGY [Mrs. Aesha K. Virani , Mrs. Hina S. Jayani] 5


Advanced Python Programming (UNIT-4) | 4321602

The screen is divided into four quadrants. The point where the turtle is initially positioned at the beginning
of your program is (0,0). This is called Home. To move the turtle to any other area on the screen, you
use .goto() and enter the coordinates like this:

import turtle

# Creating turtle screen

t = turtle.Turtle()

# Move turtle with coordinates

t.goto(100, 80)

# To stop the screen to display

turtle.mainloop()

Your output will look like this:

You’ve drawn a line from your current position to the point (100,80) on the screen.

To bring the turtle back to its home position, you type the following:

t.home()

Another way of doing this:

INFORMATION TECHNOLOGY [Mrs. Aesha K. Virani , Mrs. Hina S. Jayani] 6


Advanced Python Programming (UNIT-4) | 4321602
t.goto(0,0)

Define various turtle screen methods to change the background color, title and screen size. WINTER-
2022

Changing the Screen Title

you may want to change the title of your screen

turtle.title("My Turtle Program")

Your title bar will now display this:

Changing the Turtle Size

You can increase or decrease the size of the onscreen turtle to make it bigger or smaller. This changes only
the size of the shape without affecting the output of the pen as it draws on the screen.

Syntax of trutle.shapesize()

turtle.shapesize(stretch_wid=None, stretch_len=None, outline=None)


We would be using the above function to change the size of the turtle.

1. stretch_wid: This parameter will change the size of the turtle vertically (up and down).
2. stretch_len: This parameter will change the size of the turtle horizontally (left and right).
3. outline: This parameter will change the width size of the outline of the turtle icon.

from turtle import *


s = getscreen()
t = Turtle()

t.shapesize(stretch_wid=5, stretch_len=5, outline=1)

Screen().turtles()
Screen().exitonclick()

We import all the modules * from the turtle library.


The getscreen() function is used to return the turtle screen object on which we draw stored in variables.
Later we create a turtle object via Turtle() function stored in a variable t.
You can rename t to any other name, you wish to example my_turtle or the_turtle.
t.shapesize contains all the required dimensions, we specify the width and length in stretch_wid and
strech_len.
In this example, we have set the outline outline to 1 which is none.Screen().turtles() function returns a list of
all the turtles present on the screen.
To exit the screen we have defined Screen().exitonclick() function which would allow us to exit on click.

INFORMATION TECHNOLOGY [Mrs. Aesha K. Virani , Mrs. Hina S. Jayani] 7


Advanced Python Programming (UNIT-4) | 4321602
Output:

What are the various types of pen command in turtle? Explain them all. SUMMER-2022,
SUMMER-2023

Changing the Pen Size

We can increase or decrease the turtle's size according the requirement. Sometimes, we need thickness in the
pen. We can do this using the following example.

Example -

import turtle

# Creating turtle turtle

t = turtle.Turtle()

t.pensize(4)

t.forward(200)

turtle.mainloop()

Output:

INFORMATION TECHNOLOGY [Mrs. Aesha K. Virani , Mrs. Hina S. Jayani] 8


Advanced Python Programming (UNIT-4) | 4321602
As we can see in the above image, the pen is four times the original size. We can use it draw lines of various
sizes.

Changing the Pen color

By default, when we open a new screen, the turtle comes up with the black color and draws with black ink.
We can change it according the two things.

o We can change the color of the turtle, which is a fill color.


o We can change the pen's color, which basically a change of the outline or the ink color.

We can also change both the pen color and turtle color if we want. We suggest increasing the size of the
turtle that changes in the color can be clearly visible. Let's understand the following code.

Example -
import turtle
# Creating turtle turtle
t = turtle.Turtle()
# Increase the turtle size
t.shapesize(3,3,3)
# fill the color
t.fillcolor("blue")
# Change the pen color
t.pencolor("yellow")
turtle.mainloop()

Output:

INFORMATION TECHNOLOGY [Mrs. Aesha K. Virani , Mrs. Hina S. Jayani] 9


Advanced Python Programming (UNIT-4) | 4321602
Type the following function to change the color of both.

Example - 2:

import turtle

# Creating turtle turtle

t = turtle.Turtle()

t.shapesize(3,3,3)

# Chnage the color of both

t.color("green", "red")

t.forward(100)

turtle.mainloop()

Output:

Explanation:

In the above code, the first color is a pen color and second is a fill color.

Changing the Pen Speed

The speed of the turtle can be changed. Generally, it moves at a moderate sped over the screen but we can
increase and decrease its speed. Below is the method to modify the turtle speed.

Example -

import turtle
INFORMATION TECHNOLOGY [Mrs. Aesha K. Virani , Mrs. Hina S. Jayani] 10
Advanced Python Programming (UNIT-4) | 4321602
# Creating turtle

t = turtle.Turtle()

t.speed(3)

t.forward(100)

t.speed(7)

t.forward(100)

turtle.mainloop()

Output:

The turtle speed can vary integer values in the range 0…10. No argument is passed in the speed() function,
it returns the current speed. Speed strings are mapped to speed values as follows.

0 Fastest

10 Fast

6 Normal

3 Slow

1 Slowest

INFORMATION TECHNOLOGY [Mrs. Aesha K. Virani , Mrs. Hina S. Jayani] 11


Advanced Python Programming (UNIT-4) | 4321602
Change the Pen Direction

By default, the turtle points to the right on the screen. Sometimes, we require moving the turtle to the other
side of the screen itself. To accomplish this, we can use the penup() method. The pendown() function uses
to start drawing again. Consider the following example.

Example -

import turtle

# Creating turtle

t = turtle.Turtle()

t.fd(100)

t.rt(90)

t.penup()

t.fd(100)

t.rt(90)

t.pendown()

t.fd(100)

t.rt(90)

t.penup()

t.fd(100)

t.pendown()

turtle.mainloop()

Output:

INFORMATION TECHNOLOGY [Mrs. Aesha K. Virani , Mrs. Hina S. Jayani] 12


Advanced Python Programming (UNIT-4) | 4321602
As we can see in the above output, we have obtained two parallel lines instead of a square.

Clearing Screen

We have covered most of designing concepts of the turtle. Sometimes, we need a clear screen to draw more
designs. We can do it using the following function.

t.clear()

The above method will clear the screen so that we can draw more designs. This function only removes the
existing designs or shapes not make any changes in variable. The turtle will remain in the same position.

Resetting the Environment

We can also reset the current working using the reset function. It restores the turle's setting and clears the
screen. We just need to use the following function.

t.reset

All tasks will be removed and the turtle back to its home position. The default settings of turtle, such as
color, size, and shape and other features will be restored.

Customization in One line

Suppose we want multiple changes within the turtle; we can do it by using just one line. Below are a few
characteristics of the turtle.

o The pen color should be red.


o The fill color should be orange.
o The pen size should be 10.
o The pen speed should 7
o The background color should be blue.

Let's see the following example.

Draw circle and triangle shapes using turtle and fill them with red color. SUMMER-
2022,WINTER-2022

Example

import turtle

# Creating turtle
t = turtle.Turtle()
t.pencolor("red")
t.fillcolor("orange")
t.pensize(10)
t.speed(7)
INFORMATION TECHNOLOGY [Mrs. Aesha K. Virani , Mrs. Hina S. Jayani] 13
Advanced Python Programming (UNIT-4) | 4321602
t.begin_fill()
t.circle(75)
turtle.bgcolor("blue")
t.end_fill()
turtle.mainloop()

Output:

We used just one line and changed the turtle's characteristics. To learn about this command, you can learn
from the library official documentation.
Turtle Screen Methods
1. turtle.bgcolor()

The turtle module 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.

turtle.bgcolor()

This method is used to set or return background color of the Turtle Screen.

Syntax:

turtle.bgcolor(*args)

Example1

INFORMATION TECHNOLOGY [Mrs. Aesha K. Virani , Mrs. Hina S. Jayani] 14


Advanced Python Programming (UNIT-4) | 4321602
# importing package
import turtle

# set the background color


# of the turtle screen
turtle.bgcolor("orange")
# move turtle
turtle.forward(100)
Output :

2. turtle.bgpic()
This function is used to set a background image or return name of the current background image. It
requires only one argument “picname”. This argument can be used in different ways as follows :

If picname is a filename, set the corresponding image as background.


If picname is “nopic”, delete background image, if present.
If picname is None, return the filename of the current backgroundimage.
Syntax :

turtle.bgpic(picname=None)

Example1:
# import package
import turtle
# check background image
print(turtle.bgpic())

Output :

nopic

Example2:

# import package

import turtle

# set background image

turtle.bgpic("gfg.png")

Output :

INFORMATION TECHNOLOGY [Mrs. Aesha K. Virani , Mrs. Hina S. Jayani] 15


Advanced Python Programming (UNIT-4) | 4321602

3. turtle.delay()
This method is used to return or set the drawing delay in milliseconds. It requires only one optional
argument as a positive integer for delay.
Syntax : turtle.delay(delay)
delay : a positive integer, denoted the delay time in milliseconds, is optional
Returns : The delayed value
Example 1 :

# import package
import turtle

# turtle movement with


# normal speed
turtle.forward(100)

# slow the speed by


# turtle delay
turtle.delay(50)

# turtle movement
turtle.forward(80)
Output :

INFORMATION TECHNOLOGY [Mrs. Aesha K. Virani , Mrs. Hina S. Jayani] 16


Advanced Python Programming (UNIT-4) | 4321602
4. turtle.getcanvas()

Return the Canvas of this TurtleScreen.

No argument.

Example:
import turtle as t
cv = t.getcanvas()
#t.mainloop()
print(cv)

Output

.!scrolledcanvas

5. turtle.getshapes()

Return a list of names of all currently available turtle shapes.

Example:

import turtle as t

cv = t.getshapes()

#t.mainloop()

print(cv)

Output:

['arrow', 'blank', 'circle', 'classic', 'square', 'triangle', 'turtle']

6. turtle.window_height()

Return the height of the turtle window.

Example:

import turtle as t

cv = t.window_height()

#t.mainloop()

print(cv)

Output:

675

INFORMATION TECHNOLOGY [Mrs. Aesha K. Virani , Mrs. Hina S. Jayani] 17


Advanced Python Programming (UNIT-4) | 4321602
7. turtle.window_width()

Return the width of the turtle window.

Example:

import turtle as t

cv = t.window_width()

#t.mainloop()

print(cv)

Output:

720

Explain how loops can be useful in turtle and provide an example. SUMMER-2023

Turtle Programming Using Loops and Conditional Statements

We have learned the basic and advanced concepts of the turtle library so far. The next step is to explore
those concepts with Python's loops and conditional statements. It will give us a practical approach when it
comes to an understanding of these concepts. Before moving further, we should remember the following
concepts.

Loops - These are used to repeat a set of code until a particular condition is matched.

Conditional Statements - These are used to perform a task based on specific conditions.

for loops

Here, we will implement create a square program using for loop. For example –

Example:

t.fd(100)

t.rt(90)

t.fd(100)

t.rt(90)

t.fd(100)

t.rt(90)

t.fd(100)

t.rt(90)

We can make it shorter using a for loop. Run the below code.
INFORMATION TECHNOLOGY [Mrs. Aesha K. Virani , Mrs. Hina S. Jayani] 18
Advanced Python Programming (UNIT-4) | 4321602
Example

import turtle

# Creating turtle

t = turtle.Turtle()

for i in range(4):

t.fd(100)

t.rt(90)

turtle.mainloop()

Output:

Explanation

In the above code, for loop repeated the code until it reached at counter 4. The i is like a counter that starts
from zero and keep increasing by one. Let's understand the above loop execution step by step.

o In the first iteration, i = 0, the turtle moves forward by 100 units and then turns 90 degrees to the
right.
o In the second iteration, i = 1, the turtle moves forward by 100 units and then turns 90 degrees to the
right.
o In the third iteration, i = 2, the turtle moves forward by 100 units and then turns 90 degrees to the
right.
o In the third iteration, i = 3, the turtle moves forward by 100 units and then turns 90 degrees to the
right.

INFORMATION TECHNOLOGY [Mrs. Aesha K. Virani , Mrs. Hina S. Jayani] 19


Advanced Python Programming (UNIT-4) | 4321602
After completing the iteration, the turtle will jump out of the loop.

Example:

import turtle as t

def squre(length):

for i in range (4):

t.fd(length)

t.left(90)

squre(60)

squre(100)

squre(200)

t.mainloop()

Output:

Example:

import turtle as t

t.showturtle()

t.shape("turtle")

t.pencolor("green")

INFORMATION TECHNOLOGY [Mrs. Aesha K. Virani , Mrs. Hina S. Jayani] 20


Advanced Python Programming (UNIT-4) | 4321602
for x in range (13):

t.fd(200)

t.lt(150)

t.mainloop()

Output:

while loops

It is used to run a block of code until a condition is satisfied. The code will be terminated when it finds a
false condition. Let's understand the following example.

Example -

import turtle

# Creating turtle

t = turtle.Turtle()

n=10

while n <= 60:

t.circle(n)

n = n+10

turtle.mainloop()

INFORMATION TECHNOLOGY [Mrs. Aesha K. Virani , Mrs. Hina S. Jayani] 21


Advanced Python Programming (UNIT-4) | 4321602
Output:

As we can see in the output, we draw multiple circles using the while loop. Every time the loop executes the
new circle will be larger than the previous one. The n is used as a counter where we specified the value of n
increase in the each iteration. Let's understand the iteration of the loop.

o In the first iteration, the initial value of n is 10; it means the turtle draw the circle with the radius of
10 units.
o In the second iteration, the value of n is increased by 10 + 10 = 20; the turtle draws the circle with
the radius of 20 units.
o In the second iteration, the value of n is increased by 20 + 10 = 30; the turtle draws the circle with
the radius of 30 units.
o In the second iteration, the value of n is increased by 30 + 10 = 40; the turtle draws the circle with
the radius of 30 units.

Conditional Statement

The conditional statement is used to check whether a given condition is true. If it is true, execute the
corresponding lines of code. Let's understand the following example.

Example:

import turtle as t

u=input("Would you like to draw shape yes or no")

if u == "yes":

t.circle(50)

INFORMATION TECHNOLOGY [Mrs. Aesha K. Virani , Mrs. Hina S. Jayani] 22


Advanced Python Programming (UNIT-4) | 4321602
elif u == "no":

print("okay")

else:

print("invalid input")

t.done()

Output:

If you enter yes ,then draws a circle

If you enter no ,then print okay

If you enter anything else ,then print Invalid

INFORMATION TECHNOLOGY [Mrs. Aesha K. Virani , Mrs. Hina S. Jayani] 23


Advanced Python Programming (UNIT-4) | 4321602

1. Write a program to draw square, rectangle and circle using turtle. SUMMER-2022
2. Write a program to draw smiling face emoji using turtle. SUMMER-2022
3. Write a program for draw an Indian Flag using Turtle. SUMMER-2023
4. Write a python program to draw a chess-board using turtle. WINTER-2022
5. Write a python program to draw a Tic-Tac-Toe Board using turtle. WINTER-2022

**********
“Do not give up, the beginning is always hardest!”

INFORMATION TECHNOLOGY [Mrs. Aesha K. Virani , Mrs. Hina S. Jayani] 24

You might also like