Content Beyond Syllabus
Content Beyond Syllabus
JOSEPH’S ACD-
Format No.
COLLEGE OF ENGINEERING & TECHNOLOGY CF-CBL
Elupatti, Thanjavur – 613 403 Issue No. 01
CONTENT BEYOND SYLLABUS Rev. No. 00
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:
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
>>> 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.
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.
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
>>> 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.
>>> 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.
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.
>>> 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.
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.
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
>>> 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.
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 .
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
... t.left(45)
... t.width(i)
... t.penup()
...
>>> t.update()
Figure : A red flower using circle().