onclick() method

This method calls a function whenever the mouse is used to click on a particular coordinate.

It accepts three arguments which are:

fun– this is a function with two arguments, to which will be assigned the coordinates(x,y) of the clicked point on the canvas.

btn– this argument is assigned to one by default, which means you click the left mouse button to call a function. If you assign it to two, you will have to click both the left and right mouse button simultaneously to call a function.

add– True or False. If True, a new binding will be added, otherwise, it will replace a former binding.

I usually use one argument which is the function I want to call when I click my mouse.

Here is a program that draws a circle when you click on the turtle. Save the code snippet as click_to_draw_circle.py

Draw a circle with a mouse click

Python

1

2

3

4

5

6

7

8

9

fromturtleimportTurtle

t=Turtle()

t.screen.bgcolor("black")

t.color("orange")

defcircle(x,y):

t.circle(60)

t.onclick(circle)

Note:

The function name “circle” has two arguments, x and y which are the coordinates you will have to click to draw a circle.

ondrag() method

This method is basically used when you what to click on the turtle and move it. It accepts three arguments like the onclick() method.

Here is a program to illustrate the ondrag() method.

The code snippet below is saved as turtle_ondrag.py.

Python

1

2

3

4

5

6

7

8

9

10

fromturtleimportTurtle

t=Turtle()

t.screen.bgcolor("black")

t.color("blue")

defgoto(x,y):

t.goto(x,y)

t.ondrag(goto)

Here’s what I drew using the program above.

I drew a cup.

onrelease() method

This method is also similar to onclick and ondrag method. To understand what this method does,

I wrote a program to draw a circle when you left click on the turtle and when you remove your hand from the mouse, the circle will disappear.

Here is the code snippet and it is saved as turtle_onrelease.py

1

2

3

4

5

6

7

8

9

10

11

12

from turtle import Turtle

t=Turtle()

def draw_circle(x,y):

t.circle(50)

def erase_drawing(x,y):

t.clear()

t.onclick(draw_circle)

t.onrelease(erase_drawing)

Note:

You have to leave your hand on the left-hand button of the mouse until the circle is drawn on the screen.

When the circle has been drawn, you can then remove your hand from your mouse. Once you remove your hand from the mouse, the circle disappears.

This circle disappears because of the clear() method. The clear() method deletes the turtle’s drawing on the screen.

How to control the turtle with your keyboard

This section is going to be fun as we will control the turtle with the keyboard of our computer.

Before we write some codes, let me explain the following concepts.

onkey()

listen()

onkey()

This method is similar to onclick() method. The only differences is that the onclick() method responds to clicks on the mouse while the onkey() method responds to commands from your computer keyboard.

The onkey() method accepts two arguments which are:

fun: this is a function without any argument

keyboard command: this is basically any alphabet on your keyboard (e.g n) or any keyboard command key. e.g space, your direction keys(up, down). You have to pass this command as a string

listen()

I will avoid using any technical word because I’m as well bored with them. Basically, without including this method, the turtle won’t obey your commands.

The listen() method is like a cane you use on a child to obey your instruction.

Alright, let’s write some codes.

Project 6:

Write a program to control the turtle to move up, down, left and right using the computer keyboard. The turtle should move constantly to any pixels of your choice.

Include an undo action.

Open a new file editor and save the following code snippet as turtle_keyboard_control.py

keyboard control program

Python

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

fromturtleimportTurtle

t=Turtle()

defup():

ifnot(t.heading()==90):

t.setheading(90)

t.fd(50)

else:

t.fd(50)

defdown():

ifnot(t.heading()==270):

t.setheading(270)

t.fd(50)

else:

t.fd(50)

defright():

ifnot(t.heading()==0):

t.setheading(0)

t.fd(50)

else:

t.fd(50)

defleft():

ifnot(t.heading()==180):

t.setheading(180)

t.fd(50)

else:

t.fd(50)

defundo_button():

t.undo()

defkeyboard_commands():

t.screen.onkey(up,"Up")

t.screen.onkey(down,"Down")

t.screen.onkey(right,"Right")

t.screen.onkey(left,"Left")

t.screen.onkey(undo_button,"End")

t.screen.listen()

keyboard_commands()

t.screen.mainloop()

Don’t let the long code snippet to confuse you.

I will quicky explain the program above.

I mentioned early that :

Angle 90 sets the turtle to face the North.

Angle 180 sets the turtle to face the West.

Angle 270 sets the turtle to face the South.

Angle 360 or 0 set turtle to face the East

Alright!!!…

Now the “if”, “ else “ and “not” tells the turtle that if it’s not facing the desired direction, that it should change the direction.

t.heading() returns the current turtle’s current heading.

t.undo() undo the last action of the turtle.

The key commands are “Up”, “Down”, “Left”, “Right” and “End” which are your direction keys and end key on the keyboard. Note that they all start with capital letters.

The rest of the code snippets are easy to understand.

stamp() method

This method basically pastes the turtle shape on the canvas on the current turtle’s position.

To illustrate this, open a new file editor and save the following code snippet as turtle_stamp.py

stamp method()

Python

1

2

3

4

5

6

7

8

9

10

11

fromturtleimportTurtle

t=Turtle()

t.up()

t.setx(-50)

t.down()

t.hideturtle()

foriinrange(4):

t.fd(50)

t.stamp()

Here’s the output of the above code snippet.

Observing the above screenshot, you will see that the turtle shape appeared 4 times. This makes the concept of for loop more practical. For every 50pixels to the east, a turtle shape will appear.

How to Determine the Position of the Turtle.

position() method:

This method returns the position of the turtle, both the coordinates of the x and y axis is returned.

xcor() method:

This method returns the x coordinate of the turtle.

ycor() method:

This method returns the y coordinate of the turtle.

One more last thing before I end this tutorial.

How to Change the Title of the Turtle Screen

The default title of the turtle screen is “Python Turtle Graphics”, which can be boring.

It will be fun if your name or your friend’s name is on it. Your friends will know that you’re a Pro programmer.

To change the title of the turtle screen, use the method screen.title(). This method only accepts a string.

To illustrate this method, open a new file editor and save the following code snippet as turtle_screen_title.py

Python

1

2

3

4

5

fromturtleimportTurtle

t=Turtle()

t.screen.title("Cool Python codes")

Here is the output of the program above.

How to change the title of Python turtle.

Here are some amazing drawings I did with Python Turtle including the code snippet.

Try and study the code snippet and do a lot of experiments to come up with new designs.

The below code snippet is saved as beautiful_circles.py

Circle spiral

Python

1

2

3

4

5

6

7

8

9

10

11

12

13

14

fromturtleimportTurtle

t=Turtle()

t.screen.bgcolor("black")

colors=["red","yellow","purple"]

t.screen.tracer(0,0)

forxinrange(100):

t.circle(x)

t.color(colors[x%3])

t.left(60)

t.screen.exitonclick()

t.screen.mainloop()

Here’s the output of the above code snippet.

Beautiful circles with Python Turtle

The below code snippet is saved as beautiful_square.py

Beautiful Square

Python

1

2

3

4

5

6

7

8

9

10

11

12

13

14

fromturtleimportTurtle

t=Turtle()

t.screen.bgcolor("black")

colors=["blue","purple","red","yellow"]

t.screen.tracer(0,0)

forxinrange(300):

t.color(colors[x%4])

t.fd(x)

t.left(90)

t.screen.exitonclick()

t.screen.mainloop()

Here’s the output of the code snippet above.

Beautiful Square

The below code snippet is saved as beautiful_spiral.py

Python

1

2

3

4

5

6

7

8

9

10

11

12

13

14

fromturtleimportTurtle

t=Turtle()

t.screen.bgcolor("black")

colors=["blue","purple","red","yellow","orange","brown"]

t.screen.tracer(0,0)

forxinrange(300):

t.color(colors[x%6])

t.fd(x)

t.left(59)

t.screen.exitonclick()

t.screen.mainloop()

Here’s the output of the above code snippet.

beautiful spiral

You have come to the end of this tutorial.

Please don’t forget to:

Please if you have any questions or contributions, please leave it in the comment section.

Thanks for reading. If you enjoyed this tutorial, hit the share button. It would mean a lot to me and it helps other people to see the tutorial.

It would mean a lot to me and it helps other people to see the tutorial.

ad: Install Python and other important software on any device no matter where you are with a virtual cloud desktop by CloudDesktopOnline.com . Get additional cloud related business software such as SharePoint from Apps4Rent.com .

About the author

Rapture Godson

I am Godson; the brain behind Cool Python Codes. On this blog, I will make Python much fun and very practical. My up-to-date tutorials are based on my studies and they are very easy for you to understand.

I am a newbie of python. I got confused even from the first line: “from turtle import Turtle”.
According to what I learned from tutorial, it means “to import Turtle.py from turtle (folder / package)”. But I can’t find any Turtle.py in the source which I downloaded. The more weird is that it works. Could you tell me why?

I imported ‘beautiful_square’ and got correct result. Then, I did ‘beautiful_circles’ and it & python interpreter crashed. I restarted the python interpreter and imported ‘beautiful_circles’ and got correct result. But it crashed again once I imported ‘beautiful_square’ then.
How come? The two module can’t be imported at the same time. I even found similar phenomenon at other modules.

Importing a module doesn’t cause it been run? How can I run it except importing it. I am a newbie. I always run a module by importing it.
That program and gif image were downloaded from here. Yes, they are at the same folder. Image name is right too.

I’m using Python Interpreter at Windows. Importing command is the only way I know from tutorial to run a module at python file at interpreter. Surely, I can run invoke python interpreter to run that module from command prompt too. Any other way to run a module from python interpreter except importing it?

As you said: “Let your program and the gif image be in the same folder on your computer.”, but I got confused that where I should put that gif file. Which folder is the one so-called “your program” reside? I input that program lines in python interpreter directly, so where is my program’s folder?