0% found this document useful (0 votes)
101 views11 pages

Content Beyond Syllabus

Uploaded by

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

Content Beyond Syllabus

Uploaded by

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

ST.

JOSEPH’S ACD-
Format No.
COLLEGE OF ENGINEERING & TECHNOLOGY CF-CBL
Elupatti, Thanjavur – 613 403 Issue No. 01
CONTENT BEYOND SYLLABUS Rev. No. 00

Sub Code/Name :GE3151/PROBLEM SOLVING AND PYTHON PROGRAMMING

Course Instructor : A.CHARMILA

Year/Sem/Sec :I/I/A

Introduction

Graphical User Interfaces (GUI’s) provide a rich environment in which information can be ex- changed 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 per- forming 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.
The turtle module is an implementation of turtle graphics and uses tkinter for the creation of the underlying
graphics. Turtle graphics dates back to the 1960’s and was part of the Logo programming language.1 This chapter
provides an introduction to using the graphics capabilities of the turtle module and demonstrates the creation of
simple images and simple GUI’s for games and applications. We will not delve into the details of building and
designing GUI’s, but many of the skills developed here can be applied to more complicated GUI designs if you
wish to pursue that in the future. In addition to helping you gain practical programming skills, learning to use
turtle graphics is fun and it enables you to use Python to be visually creative!

Turtle Basics

Among other things, the methods in the turtle module allow us to draw images. The idea behind the turtle part of
“turtle graphics” is based on a metaphor. Imagine you have a turtle on a canvas that is holding a pen. The pen can
be either up (not touching the canvas) or down (touching the canvas). Now think of the turtle as a robot that you
can control by issuing commands. When the pen it holds is down, the turtle leaves a trail when you tell it to move
to a new location. When the pen is up, the turtle moves to a new position but no trail is left. In addition to
position, the turtle also has a heading, i.e., a direction, of forward movement. The turtle module provides
commands that can set the turtle’s position and heading, control its forward and backward movement, specify the
type of pen it is holding, etc. By controlling the movement and orientation of the turtle as well as the pen it is
holding, you can create drawings from the trails the turtle leaves.
Importing Turtle Graphics
In order to start using turtle graphics, we need to import the turtle module. Start Python/IDLE and type the
following:

Importing the turtle module.

>>> import turtle as t

This imports the turtle module using the identifier t. By importing the module this way we access the methods
within the module using t.<object> instead of turtle.<object>. To ensure that the module was properly imported,
use the dir()function

Using dir()to view the turtlemodule’s methods and attributes.

>>> dir(t)
[’Canvas’, ’Pen’, ’RawPen’, ’RawTurtle’, ’Screen’, ’ScrolledCanvas’,
’Shape’, ’TK’, ’TNavigator’, ’TPen’, ’Tbuffer’, ’Terminator’,
’Turtle’, ’TurtleGraphicsError’, ’TurtleScreen’, ’TurtleScreenBase’,
’Vec2D’, ’_CFG’, ’_LANGUAGE’, ’_Root’, ’_Screen’, ’_TurtleImage’,
’ all ’, ’ builtins ’, ’ cached ’, ’ doc ’, ’ file ’,

The list returned by the dir() function in Listing 13.2 has been truncated—in all, there are 173 items in this list.
To learn more about any of these attributes or methods, you can use the help() function. For example, to learn
about the forward() method, enter the statement shown in line 1 of Listing 13.3.
Learning about the forward()method using help().

From this we learn, as shown in lines 12 and 13, that this method moves “the turtle forward by the specified
distance, in the direction the turtle is headed.” We also learn that there is a shorter name for this method: fd().
Drawing a line with a length of 100 units.
>>> t.fd(100)

A graphics window should appear in which you see a small arrow 100 units to the right of the center of the
window.2 A thin black line is drawn from the center of the window to the tail of the arrow. The arrow represents
our “turtle” and the direction the arrow is pointing indicates the

current heading. The fd() method is a shorthand for the forward() method—the two methods are identical. fd()
takes one integer argument that specifies the num- ber of units you want to move the turtle forward in the
direction of the current heading.3 If you provide a negative argument, the turtle moves backwards the specified
amount. Alternatively, to move backward one can call either backward(), back(), or bk().
The default shape for our turtle is an arrow but if we wanted to have it look like a turtle we could type the
command shown in Listing 13.5.
Changing the shape of the turtle.
>>> t.shape("turtle")

This replaces the arrow with a small turtle. We can change the shape of our turtle to a number of other built in
shapes using the shape() method. We can also create custom shapes although we won’t cover that hereWhen it
first opens, this window may appear behind previously opened windows. So, you may have to search for

By default the units correspond to pixels, i.e., individual picture-elements or dots on your screen, but one can reset
the coordinates so that the units can correspond to whatever is most convenient to generate the desired image.

A line of length 100 produced by the fd()method.

Even though our turtle’s shape appears on the graphics window, the turtle is not truly part of our
drawing. The shape of the turtle is there to help you see the turtle’s current position and heading, but you
need to issue other commands, such as fd(), to create a drawing. If you have created a masterpiece and
you no longer want to see the turtle in your graphics window, you can enter the command shown in
Listing 13.6.

Command to hide the turtle’s shape from the screen.


>>> t.hideturtle()

This hides the image that currently represents the turtle. In fact, you can continue to create lines even
when the turtle’s shape is hidden, but you will not be able to see the turtle’s current position nor its
heading. If you want to see the turtle again, simply issue the command shown in Listing 13.7.
Making the turtle visible.
>>> t.showturtle()

The turtle’s heading can be controlled using one of three methods: left(), right(), and setheading(); or
the shorter aliases of lt(), rt(), and seth(), respectively. left() and right() turn the turtle either to the left or
right, respectively, by the number of degrees given as the argument. These turns are relative to the turtle’s
current heading. So, for example, left(45) causes the turtle to turn 45 degrees to the left. On the other
hand, setheading()and seth()
Figure : A square box
To set the absolute heading of the turtle. A heading of 0 is horizontally to the right (i.e., east), 90 is up
(i.e., north), 135 is up and to the left (i.e., northwest), and so on.
Assuming you have previously entered the command of Listing 13.4, enter the commands in Listing
13.8. After doing this you should see a square drawn in the graphics window

Commands to change the turtle’s heading and draw a square box.

>>> t.left(90)
>>> t.fd(100)
>>> t.left(90)
>>> t.fd(100)

What if we want to change the location of the turtle without generating a line? We can ac- complish
this by calling the method penup() before we enter commands to move the turtle. To re- enable drawing,
we call the method pendown().
We can also move the turtle to a specific position within the graphics window by using the
setposition() method (or its aliases setpos() and goto()). setposition()’s argu- ments are the desired x and
yvalues. The change of position does not affect the turtle’s heading. If the pen is down, when you call
setposition() (or its aliases), a straight line is drawn from that starting point to the position specified by the
arguments. To demonstrate the use of penup(), pendown(), and setposition(), issue the commands shown
in Listing The resulting image .

Result of moving the turtle without drawing a line and then, once at the new location, drawing a line.
Using penup()and setposition()to move the turtle without making a line.
>>> t.penup()
>>> t.setposition(100, -100)
>>> t.pendown()
If we want to erase everything that we previously drew, we can use either the clear() or reset()
methods. clear() clears the drawing from the graphics window but it leaves the turtle in its current position
with its current heading. reset() clears the drawing and also returns the turtle to its starting position in the
center of the screen. To illustrate the behavior of clear(), enter the statement shown in Listing 13.10.

Using the clear()method to clear the image.


>>> t.clear()
You should now see that the drawing that our turtle generated has been cleared from the screen but the
turtle is still in the state that you last specified. To demonstrate what reset() does, enter the command

Resetting the turtle and clearing the image.

>>> t.reset()

The turtle is moved back to the center of the screen with its original heading. Note that we do not need
to call clear() before we call reset(). reset() will also clear the drawing—in the above example they were
done sequentially solely for demonstrating their behavior.

Basic Shapes and Using Iteration to Generate Graphics

The commands shown in Listing 13.8 that we used to draw a square box would be rather cum- bersome to
type repeatedly if we wanted to draw more than one box. Observe that we are typing the same commands
four times. As you already know, this sort of iteration can be accomplished in a much simpler way using a
for-loop. Let’s create a function called square() that draws a square using a for-loop. The function takes
one argument which is the length of the square’s sides. Enter the commands in Listing 13.12 that define
this function and then call it three times, each time with a different length. The result should be the
squares that are shown in Fig. 13.4.

A function that draws a square using a for-loop.


>>> def square(length):
... for i in range(4):
... t.fd(length)
... t.left(90)
...
>>> square(60)
Building a square from straight lines is relatively straightforward, but what if we want to draw circles?
Turtle provides a method called circle() that can be used to tell the turtle to draw a complete circle or only
a part of a circle, i.e., an arc. The circle() method has one mandatory argument which is the radius of the
circle. Optional arguments specify the “extent,” which is the degrees of arc that are drawn, and the
“steps,” which are the number of straight-line segments used to approximate the circle. If the radius is
positive, the circle is drawn (starting from the current position) by turning to the left (counterclockwise).
If the radius is negative, the circle is drawn (starting from the current position) by turning to the right
(clockwise). To demonstrate this, enter the commands After issuing these commands, the graphics
window should appear

Listing 13.13 Drawing circles using the circle()method.


>>> t.reset() # Remove previous drawings and reset turtle.
>>> t.circle(100) # Draw circle counterclockwise with radius 100.
>>> t.circle(-50) # Draw circle clockwise with radius 50.
BASIC SHAPES AND USING ITERATION TO GENERATE GRAPHICS

Drawing multiple boxes with square()of Listing

Figure : The circles drawn by the code in Listing


BASIC SHAPES AND USING ITERATION TO GENERATE GRAPHICS
Controlling the Turtle’s Animation Speed
If you have been watching the turtle move in the graphics window as you issue commands, you will have
noticed that the turtle goes through its motions relatively slowly. Sometimes watching the turtle move can
be helpful but there are ways that you can speed up the movement (and hence speed up the drawing
process). There is a speed() method for which the argument specifies the speed as an integer between 0
and 10. A value of 1 is the slowest speed. Speeds generally increase with increasing arguments so that 2 is
faster than 1, three is faster than 2, and so on. However, rather than 10 being be fastest speed, it is actually
the second to the fastest speed—0 is the fastest speed. The default speed is 3. To demonstrate this, issue
the commands

Speeding up the animation by using the speed()method.

>>> t.reset()
>>> t.speed(0)
>>> t.circle(100)

The image should be the same as 13.5, but it should render noticeably faster than it did previ- ously.
However, even though supplying the speed() method with an argument of 0 makes the animation faster, it
is still quite slow if we want to draw a more complex drawing. In order to make our drawing appear
almost immediately we can make use of the tracer() method. tracer() takes two arguments. One controls
how often screens should be updated and the other controls the delay between these update. To obtain the
fastest possible rendering, both these arguments should be set to zero as shown in Listing 13.15.

Turning off the animation with tracer().


>>> tracer(0, 0)

By calling tracer() with bother arguments set to zero, we are essentially turning off all animation and
our drawings will be drawn “immediately.” However, if we turn the animation off in this way we need to
explicitly update the image with the update() method after we are done issuing drawing commands.
If you want to reset tracer() to its original settings, its arguments should be 1 and 10, as shown in
Listing 13.16.

Restoring animation to the default settings.


>>> tracer(1, 10)
Colors and Filled Shapes

Now that we know how to create some basic shapes, let’s explore how we can create more complex
images. In order to change the color of our turtle’s pen we can use the color() method as shown in line 2 of
Listing

Changing the color of the turtle’s pen.

>>> t.reset()
>>> t.color("blue")

This change the turtle’s pen to blue. There are actually numerous ways of specifying a color in
Python’s implementation of turtle graphics. You can, as shown in Listing , specify a color via a
string.4Alternatively, we can specify a color by providing numeric values the specify the amount of red,
green, and blue. To learn more about the use of colors, use the help() function to read about t.coloror
t.pencolor.

Figure : A blue line with a thickness and width of 100.

We can also change the thickness of the turtle’s pen by using the pensize() method and passing it an
integer argument that specifies the thickness. This is demonstrated in Listing 13.18. After issuing these
commands (and those of Listing 13.17), you will see that a thick blue line has been drawn in the graphics
window
COLORS AND FILLED SHAPES
Changing the thickness of the turtle’s pen.
>>> t.pensize(100)
>>> t.fd(100)
We can also change the background color of the graphics window. To demonstrate this, you should
enter the commands of Listing .

Changing the background color of the window.


>>> t.bgcolor("blue") # Change the background to blue.
>>> t.bgcolor("white") # Change it back to white.
Let’s take what we have learned so far and draw a more complex image. Enter the commands shown
Listing 13.20. The for-loop that starts in line 3 sets the heading to angles between 0 and 345 degrees,
inclusive, in 15 degree increments. For each of these headings it draws a circle with a radius of 100. (Note
that a heading of 360 is the same as a heading of 0, so that why a circle is not draw with a heading of 360
degrees.) The resulting image

Creating a red flower.


>>> t.reset()
>>> t.color("red")
>>> for angle in range(0, 360, 15):
... t.seth(angle)

We can also use iteration to change the color and thickness of the turtle’s pen more dynamically. As an
example, try typing the commands shown in Listing 13.21. This should result in the image

Code the creation of a colorful spiral.


>>> colors = ["blue", "green", "purple", "cyan", "magenta", "violet"]
>>> t.reset()
>>> t.tracer(0, 0)
>>> for i in range(45):
... t.color(colors[i % 6])
... t.pendown()
... t.fd(2 + i * 5)

... t.left(45)
... t.width(i)
... t.penup()
...
>>> t.update()
Figure : A red flower using circle().

Figure : A colorful spiral

COURSE INSTRUCTOR HOD

You might also like