Institute of Computer Science
  1. Courses
  2. 2018/19 spring
  3. Computer Programming (LTAT.03.001)
ET
Log in

Computer Programming 2018/19 spring

  • Home

Before session 10

Graphics

This week we do not have a video lecture. Instead there is a reading material. As you go through the material, run the examples and solve two homework tasks (in yellow boxes).

Part I: Turtle

There are many modules in Python that provide very powerful features. One of the widely used modules is math. This module contains implementations of well-known mathematical functions; therefore, we don’t have to code such functions ourselves. For example:

from math import *

print(sin(1))
print(ceil(3.4))

Other modules can send emails or fetch web pages. The one we’ll have a close look at now is turtle. This module allows us to draw shapes and patterns.

Our first turtle program

The following lines import the module turtle and draw a rectangle.

from turtle import *

forward(300)
left(90)
forward(200)

exitonclick()

When you run this program, a new window pops up:

Here is a couple of things you need to understand in this program.

  • The first line tells Python to load the module turtle.
  • On lines 2-4, we instruct the turtle to draw two sides of the rectangle: move forward, turn left, and move forward again.
  • The last line is also very important. When we invoke the function exitonclick, it pauses the execution of the program, and waits for the user to click the mouse somewhere in the window. When the click occurs, Python closes the turtle window and exits (stops execution of) the program.

Complete the rectangle!

Modify the program by adding commands which will complete drawing the rectangle.

The turtle module contains many functions. For example, we can change the color of the line by calling color("red") - this statement causes the next line to be red. Besides changing the color, we can also change the width of the line, the position of drawing arrow in the window, the angle it is facing to etc. Also it is possible to change background color, title text, size and position of the window. Try out the following program.

from turtle import *

setup(800, 600)     	# set the window size to 800 by 600 pixels
bgcolor("lightgreen")	# set the window background color
title("Second program")	# set the window title
color("blue")       	# make the line blue
pensize(3)          	# set the width of the line
forward(300)
left(120)
forward(300)

exitonclick()

Running this program will create a window that looks like this:

When we run this program, the window pops up and remains on the screen until we click on it.

Extend the program!

Modify this program as follows.

  1. Before creating the window, the program prompts the user for the desired background color. While the window is on the screen, the program allows to modify its color according to user’s wish. (Hint: you can find a list of permitted color names here: here. The website contains some unusual color names such as “peach puff” and “HotPink”.)
  2. Modify the program so that the user can set the color of the line.
  3. Do the same for line width. (Hint: your dialog with the user returns a string, but turtle’s pensize function expects an integer as an argument, so you’ll need to convert the string into an integer before passing it to the pensize function.)

Loops to simplify a turtle program

To draw a square, we need to do the same actions – move forward and turn – four times. Instead of 8 lines of code to draw the four sides of a square, it is possible to draw the square in three lines:

from turtle import *

for i in range(4):
	forward(250)
	left(90)

exitonclick()

The function range(4) provides the values [0, 1, 2, 3] to execute loop body four times.

We could have used four string values. Consider the following program. On each iteration, variable clr is assigned one color from the list.

from turtle import *

for clr in ["yellow", "red", "purple", "blue"]:
	color(clr)
	forward(250)
	left(90)

exitonclick()

In this program, the value of clr is used to change the color of the line. Each iteration causes clr to take the next color from the list.

A few more turtle functions

Turtle can also work with negative values of angles or distances. For example, forward(-100) forces the turtle to move backwards, and left(-30) forces it to turn to the right. However, turning 30 degree to the left will produce the same result as turning 330 degrees to the right. The on-screen rotation animation will be slightly different in both cases - check whether the turtle turns clockwise or counter-clockwise!

The later observation might indicate that we don’t need to use both methods (to turn either to the left or to the right). We can be minimalists, and use just one of the methods. Nevertheless, utilizing both methods can simplify the code and make it easier to understand.

Finally, it has to be mentioned that there is a method to move backward. (If you are very nerdy, you might enjoy saying backward(-100) to move forward!)

The pen (yes, we can call this arrow as a pen) can be picked up or put down. This allows the turtle to move the pen to a different place without drawing a line. Check the following lines of code:

penup()
forward(100)     # this moves the pen, but no line is drawn
pendown()

Different shapes can be assigned to the pen. The ones available "out of the box" are arrow, blank, circle, classic, square, triangle, and turtle. You can change the shape of the pen as follows:

shape("turtle")

You can also speed up or slow down the animation. In other words, you can specify how quickly the pen moves and turns on the screen. The speed settings can be set between 1 (the slowest) to 10 (the fastest). But if you set the speed to 0, it has a special meaning – turn off the animation mode and draw as fast as possible.

speed(10)

We can "stamp" pen's footprint into the canvas, and it remains visible after the pen has moved to somewhere else. Stamping works even when the pen is up.

Let’s try out an example that shows some of these features:

from turtle import *

setup(800, 600)
bgcolor("lightgreen")
title("Spiral")
shape("turtle")
color("blue")
penup()                 	# this is new
size = 20
for i in range(30):
	stamp()             	# put a print
	size = size + 3     	# increase the step size on every iteration
	forward(size)       	# move the turtle along
	right(24)           	# and turn it

exitonclick()

The output of the program is shown in the picture below:

The turtle module also allows us to draw shapes and fill them with colors. Choose the color (with color("red") for example) for the shape to be filled. Function begin_fill has to be called before drawing a shape and end_fill fills the shape with the color.

The function circle draws a circle.

The flag of Japan can be drawn as follows:

from turtle import *

setup(600, 400)
title("Flag of Japan")
speed(10)

penup()
right(90)
forward(100)
left(90)
pendown()

color("red")
begin_fill()
circle(100)
end_fill()

exitonclick()

Exercise 1: Grid

Write a program that prompts the user for two integers, m and n, and draws a grid of m by n cells with the turtle. Each cell in the grid should be a square, and its side length should be a fixed integer in the interval from 40 to 50 pixels.

Part II: EasyGUI

So far we have created command line programs. This means that we, as users, can interact with the program via the command line. However, nearly all programs we use daily (web browser, text editor, Skype, etc) expect that we interact with them via buttons, text fields, etc. This way of communication with the program is called graphical user interface (GUI).

The turtle module is very similar to a drawing canvas. The module allows us to draw nice pictures (like in MS Paint :)) but it doesn’t actually allow us to communicate with the program – the module turtle is not a GUI. It is simply a fun drawing module. :)

To create a Python program with a GUI, we can use the EasyGUI module. EasyGUI is a module for creating a very simple and easy GUI in Python. If you haven't the module already installed in Thonny, please install it.

Our first easygui program

Let’s try to write a couple of lines in Python to create a dialog box with a message.

from easygui import *     # to use EasyGui, we must import it.

msgbox("My first graphical user interface!!") # message box

The output should look like this:

It is the simplest dialogue window. However, we might like to give the user more options than just pressing OK. The next window has our own set of buttons:

from easygui import *

buttons = ["easy", "ok", "difficult"]
pressed = buttonbox("Programming is ", choices = buttons)
msgbox("You think that programming is " + pressed + "!")

It will ask this question:

and then show a message box with the selected choice:

When the user clicks a button, buttonbox() returns the text of the choice which is then saved into the variable pressed. If the user closes the dialogue window, then None is returned.

A buttonbox function is good for offering the user a small selection of short choices. But if there are many choices, or the text of the choices is long, then a better strategy would be to use a choicebox.

from easygui import *

mychoices = ["my favorite", "easy", "ok", "difficult"]
pressed = choicebox("Programming is ", choices = mychoices)
if pressed == None:
	msgbox("You did not choose anything, you little rebel!")
elif pressed == "my favorite":
	msgbox("Programming is your favorite course! As it should be!")
else:
	msgbox("So you think that programming is " + pressed + ", hmm, interesting!")

This will generate the following dialogue window:

and show a message based on the selected choice:

Letting the user enter some information

To allow the user to enter some information, we can use enterbox. The module also has a separate function to ask the user for integers – integerbox. Nice thing is that you can specify the upper and lower case for the required input, and the integerbox checks automatically if the input is a number. If not, integerbox will ask the user for an integer once again.

from easygui import *

name = enterbox("Hello stranger, what's your name?")
age = integerbox("How old are you?", lowerbound = 1, upperbound = 150)
if name == None or age == None or name == "":
    msgbox("Why do you have to rebel, enter things like a normal human!!")
else:
    msgbox("Hello " + str(age)  + " year old " + name + "!")

The program asks two questions. The first question is created using enterbox:

and the second one with integerbox:

Finally, a message is shown with msgbox:

There are many more different functions you can use in the EasyGUI module. For example, you can also add images to your GUI. To find out more about EasyGUI, check its web page.

Exercise 2: Age

Write a program that prompts the user for his/her name and birth date (day, month, year). All prompts should use EasyGUI input boxes. It can be assumed that the data are entered correctly. Then, again using EasyGui, the program displays a box, which contains: 1) a greeting to the user, 2) birth date entered, 3) the age of the user as of today.

For example, the result should look like this:

Hint. To find the current date, you can use the datetime module.

Quiz

Go to Moodle and solve the tenth quiz.

Submit your solutions

Two exercises have been presented in the text above (in yellow boxes). Go to Moodle and upload your solutions under Homework 10 (filenames home1.py and home2.py).

The autograder exists but currently doesn't check the correctness of graphical output.

  • Institute of Computer Science
  • Faculty of Science and Technology
  • University of Tartu
In case of technical problems or questions write to:

Contact the course organizers with the organizational and course content questions.
The proprietary copyrights of educational materials belong to the University of Tartu. The use of educational materials is permitted for the purposes and under the conditions provided for in the copyright law for the free use of a work. When using educational materials, the user is obligated to give credit to the author of the educational materials.
The use of educational materials for other purposes is allowed only with the prior written consent of the University of Tartu.
Terms of use for the Courses environment