Рисунки для черепашки питон

turtle — Turtle graphics¶

Turtle graphics is a popular way for introducing programming to kids. It was part of the original Logo programming language developed by Wally Feurzeig, Seymour Papert and Cynthia Solomon in 1967.

Imagine a robotic turtle starting at (0, 0) in the x-y plane. After an import turtle , give it the command turtle.forward(15) , and it moves (on-screen!) 15 pixels in the direction it is facing, drawing a line as it moves. Give it the command turtle.right(25) , and it rotates in-place 25 degrees clockwise.

Turtle can draw intricate shapes using programs that repeat simple moves.

../_images/turtle-star.png

from turtle import * color('red', 'yellow') begin_fill() while True: forward(200) left(170) if abs(pos())  1: break end_fill() done() 

By combining together these and similar commands, intricate shapes and pictures can easily be drawn.

The turtle module is an extended reimplementation of the same-named module from the Python standard distribution up to version Python 2.5.

It tries to keep the merits of the old turtle module and to be (nearly) 100% compatible with it. This means in the first place to enable the learning programmer to use all the commands, classes and methods interactively when using the module from within IDLE run with the -n switch.

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.

The object-oriented interface uses essentially two+two classes:

  1. The TurtleScreen class defines graphics windows as a playground for the drawing turtles. Its constructor needs a tkinter.Canvas or a ScrolledCanvas as argument. It should be used when turtle is used as part of some application. The function Screen() returns a singleton object of a TurtleScreen subclass. This function should be used when turtle is used as a standalone tool for doing graphics. As a singleton object, inheriting from its class is not possible. All methods of TurtleScreen/Screen also exist as functions, i.e. as part of the procedure-oriented interface.
  2. RawTurtle (alias: RawPen ) defines Turtle objects which draw on a TurtleScreen . Its constructor needs a Canvas, ScrolledCanvas or TurtleScreen as argument, so the RawTurtle objects know where to draw. Derived from RawTurtle is the subclass Turtle (alias: Pen ), which draws on “the” Screen instance which is automatically created, if not already present. All methods of RawTurtle/Turtle also exist as functions, i.e. part of the procedure-oriented interface.

The procedural interface provides functions which are derived from the methods of the classes Screen and Turtle . They have the same names as the corresponding methods. A screen object is automatically created whenever a function derived from a Screen method is called. An (unnamed) turtle object is automatically created whenever any of the functions derived from a Turtle method is called.

To use multiple turtles on a screen one has to use the object-oriented interface.

In the following documentation the argument list for functions is given. Methods, of course, have the additional first argument self which is omitted here.

Источник

Простое рисование с помощью черепашки¶

У неё есть функции в стиле turtle.forward(. ) и turtle.left(. ) , с помощью которых черепашка может двигаться.

Перед тем как начать работу с черепашкой, необходимо импортировать соответствующий модуль. Мы рекомендуем экспериментировать с ней в интерактивной оболочке (для начала), т.к. при использовании файлов придётся заниматься дополнительной утомительной работой. Перейди в терминал и введи:

_images/default.png

Not seeing anything on Mac OS? Try issuing a command like turtle.forward(0) and looking if a new window opened behind your command line.

Используешь Ubuntu и получаешь сообщение об ошибке “No module named _tkinter”? Установи отсутствующий необходимый пакет: sudo apt-get install python3-tk

While it might be tempting to just copy and paste what’s written on this page into your terminal, we encourage you to type out each command. Typing gets the syntax under your fingers (building that muscle memory!) and can even help avoid strange syntax errors.

_images/forward.png

_images/left.png

Функция turtle.forward(. ) заставляет черепашку двигаться вперёд на указанное расстояние. turtle.left(. ) приказывает черепашке повернуться влево на указанную градусную меру угла. А turtle.backward(. ) и turtle.right(. ) действуют анлогично — первая заставляет черепашку двигаться назад, а вторая — поворачиваться вправо.

Если ты хочешь начать заново, введи turtle.reset() , чтобы стереть рисунок. Мы рассмотрим turtle.reset() подробнее немного позже.

Стандартная “черепашка” – всего лишь треугольник. Это не интересно! Придадим ей нормальный вид командой turtle.shape() :

If you put the commands into a file, you might have recognized that the turtle window vanishes after the turtle finished its movement. (That is because Python exits when your turtle has finished moving. Since the turtle window belongs to Python, it terminates as well.) To prevent that, just put turtle.exitonclick() at the bottom of your file. Now the window stays open until you click on it:

import turtle turtle.shape("turtle") turtle.forward(25) turtle.exitonclick() 

Python — язык программирования, в котором крайне важны отступы в коде. Подробности мы узнаем позже, в главах про функции, но сейчас тебе просто необходимо запомнить, что лишний пробел или символ табуляции перед строкой может вызвать ошибку.

Рисуем квадрат¶

You’re not always expected to know the anwer immediately. Learn by trial and error! Experiment, see what python does when you tell it different things, what gives beautiful (although sometimes unexpected) results and what gives errors. If you want to keep playing with something you learned that creates interesting results, that’s OK too. Don’t hesitate to try and fail and learn from it!

Упражнение¶

Нарисуй квадрат, как на рисунке ниже:

_images/square.png

Для квадрата тебе понадобится прямоугольный, т.е. 90-градусный, угол.

Решение¶

turtle.forward(50) turtle.left(90) turtle.forward(50) turtle.left(90) turtle.forward(50) turtle.left(90) turtle.forward(50) turtle.left(90) 

Notice how the turtle starts and finishes in the same place and facing the same direction, before and after drawing the square. This is a useful convention to follow, it makes it easier to draw multiple shapes later on.

Дополнительно¶

If you want to get creative, you can modify your shape with the turtle.width(. ) and turtle.color(. ) functions. How do you use these functions? Before you can use a function you need to know its signature (for example the number of parameters and what they mean.) To find this out you can type help(turtle.color) into the Python shell. If there is a lot of text, Python will put the help text into a pager, which lets you page up and down. Press the q key to exit the pager.

NameError: name 'turtle' is not defined

когда пытаешься просмотреть справку? В Python необходимо импортировать имена, перед тем, как обращаться к ним, т.е. в нашем случае необходимо выполнить import turtle перед help(turtle.color) .

Также найти информацию о функциях можно в онлайн-документации.

Если ты допустил ошибку, то ты можешь воспользоваться командой turtle.reset() , чтобы стереть рисунок, либо командой turtle.undo() ., чтобы отменить последние действия.

As you might have read in the help, you can modify the color with turtle.color( colorstring ) . These include but are not limited to “red,” “green,” and “violet.” See the colours manual for an extensive list.

Рисуем прямоугольник¶

Упражнение¶

Ты тоже можешь нарисовать прямоугольник?

_images/rectangle.png

Решение¶

turtle.forward(100) turtle.left(90) turtle.forward(50) turtle.left(90) turtle.forward(100) turtle.left(90) turtle.forward(50) turtle.left(90) 

Дополнительно¶

How about a triangle? In an equilateral triangle (a triangle with all sides of equal length) each corner has an angle of 60 degrees.

Больше квадратов¶

Упражнение¶

Now, draw a tilted square. And another one, and another one. You can experiment with the angles between the individual squares.

_images/tiltedsquares.png

На изображении показан поворот черепашки на 20 градусов. Ты же можешь попробовать, например, 30 или 40.

Решение¶

turtle.left(20) turtle.forward(50) turtle.left(90) turtle.forward(50) turtle.left(90) turtle.forward(50) turtle.left(90) turtle.forward(50) turtle.left(90) turtle.left(30) turtle.forward(50) turtle.left(90) turtle.forward(50) turtle.left(90) turtle.forward(50) turtle.left(90) turtle.forward(50) turtle.left(90) turtle.left(40) turtle.forward(50) turtle.left(90) turtle.forward(50) turtle.left(90) turtle.forward(50) turtle.left(90) turtle.forward(50) turtle.left(90) 

© Авторские права 2012–2014, OpenTechSchool and contributors.
Создано с помощью Sphinx 1.3.1.

Источник

Читайте также:  Python tkinter entry password
Оцените статью