SoFunction
Updated on 2025-03-03

Example of code for drawing cherry blossom trees using Python's turtle module

Example of code for drawing cherry blossom trees using Python's turtle module

Updated: April 7, 2024 08:34:05 Author: Xiaoyu, who worked hard
Python's turtle module is an intuitive graphical programming tool, allowing users to draw various shapes and patterns by controlling the movement of turtles on the screen. In the following article, I will use a vivid example - drawing a cherry blossom tree picture - to deeply explore the practicality of the turtle module. Friends who need it can refer to it.

introduction

Python's turtle module is an intuitive graphical programming tool that allows users to draw various shapes and patterns by controlling the movement of turtles on the screen. The unique feature of the turtle module is its simple and easy-to-understand operation method and its interaction with users. Users can easily write programs to control the turtle's action path by using basic commands such as forward, backward, left, and right, thereby creating colorful works. It's like giving instructions to a turtle to leave traces on the screen.

In the following article, I will explore the practicality of the turtle module in depth with a vivid example - drawing a cherry tree picture.

Understand the turtle module

When creating this vivid cherry tree picture, we will take advantage of a series of key features of the turtle module, including:

  • Initialize and set the canvas
    • (): Create a new turtle object to draw the graphics.
    • (): Get the current canvas object and can operate on it, such as setting the background color.
    • (bg='wheat'): Set the background color of the canvas to wheat color, providing a natural background for the cherry blossom trees.
  • Controlling turtle behavior
    • (): Hide the turtle icon to make the drawing cleaner.
    • (0): Set the turtle to move the fastest and speed up the drawing process.
    • ()and(): Controls whether the turtle's pen touches the canvas, used to start and end drawing.
  • Draw a graph
    • (branch)and(branch): Let the turtle move forward or backward, drawing branches.
    • (20 * a)and(40 * a): Controls the steering of the turtle, used to draw branch forks.
    • ('lightcoral')and('sienna'): Set the color of the turtle pen to draw cherry blossom branches of different colors.
  • Recursively drawing cherry blossom trees
    • Tree(branch, t): Defines a recursive function to draw the trunk and branches of a cherry tree. Recursion is a common technique in programming that simplifies repetitive code and makes drawing complex structures such as trees simple.
  • Drawing cherry blossom petals
    • Petal(m, t): Defines a function to draw multiple cherry blossom petals. Through loops and random number generation, the effect of cherry blossom petals falling with the wind is simulated.

Implement code

import turtle as T
import random

# Function to draw cherry blossom trees, parameters are branch length and drawing turtle objectdef draw_tree(trunk_length, turtle_obj):
    if trunk_length > 3:
        # Determine color and thickness based on the length of the branch        if 8 <= trunk_length <= 12:
            color = 'snow' if (0, 1) == 0 else 'lightcoral'
            turtle_obj.pensize(trunk_length / 3)
        elif trunk_length < 8:
            color = 'snow' if (0, 1) == 0 else 'lightcoral'
            turtle_obj.pensize(trunk_length / 2)
        else:
            color = 'sienna'
            turtle_obj.pensize(trunk_length / 10)
        turtle_obj.color(color)  # Set color        turtle_obj.forward(trunk_length)  # Draw branches forward        angle_a = 20 * ()  # Random angle a        turtle_obj.right(angle_a)  # Turn right        branch_reduction = 10 * ()  # Random reduction        draw_tree(trunk_length - branch_reduction, turtle_obj)  # Recursive painting subtle branches        turtle_obj.left(2 * angle_a)  # To the left        draw_tree(trunk_length - branch_reduction, turtle_obj)  # Recursive painting subtle branches        turtle_obj.right(angle_a)  # Slewing angle a        turtle_obj.penup()  # Lift the pen        turtle_obj.backward(trunk_length)  # Draw branches backwards        turtle_obj.pendown()  # Put down the pen
# Function to draw cherry blossom petals, parameters are the number of petals and drawing turtle objectdef draw_petals(petal_count, turtle_obj):
    for _ in range(petal_count):
        turtle_obj.penup()  # Lift the pen        distance = 200 - 400 * ()  # The distance from the random petals falling        turtle_obj.forward(distance)  # Move forward        turtle_obj.left(90)  # Turn        turtle_obj.forward(10 - 20 * ())  # Random petal size        turtle_obj.down()  # Put down the pen        turtle_obj.color('lightcoral')  # Set petal color        turtle_obj.begin_fill()  # Start filling color        turtle_obj.circle(1)  # Draw a circular petal        turtle_obj.end_fill()  # End fill color        turtle_obj.penup()  # Lift the pen        turtle_obj.backward(distance)  # Move backwards        turtle_obj.right(90)  # Turn
# Initialize the drawing environmentturtle_obj = ()
turtle_screen = turtle_obj.getscreen()
turtle_screen.bgcolor("wheat")  # Set the background color to wheat colorturtle_obj.hideturtle()  # Hide turtle iconturtle_obj.speed(0)  # Set the drawing speed to the fastestturtle_obj.left(90)  # Turnturtle_obj.penup()  # Lift the penturtle_obj.backward(150)  # Move backwardsturtle_obj.pendown()  # Put down the penturtle_obj.color("sienna")  # Set the brush color to ochre
# Draw cherry blossom trees and petalsdraw_tree(60, turtle_obj)
draw_petals(200, turtle_obj)

# Click the window to close the programturtle_screen.exitonclick()

Summarize

Through the study and practice of this article, we have mastered the skills of using Python's turtle module to create cherry tree drawings. In this process, we have gained an in-depth understanding of the basic commands and recursion of the turtle module, which are important foundations for building more complex projects. I also hope that readers can apply this knowledge to their projects. Whether it is drawing other natural scenes or creating abstract art works, it can be achieved with the help of the turtle module.

The above is the detailed content of the code example of using Python's turtle module to draw cherry blossom trees. For more information about Python turtle drawing cherry blossom trees, please follow my other related articles!

  • Python
  • turtle
  • Cherry blossom tree

Related Articles

  • Example of factorial sum accumulation sum

    Today, the editor will share with you an example of the python factorial sum accumulation sum, which is of good reference value and hope it will be helpful to everyone. Let's take a look with the editor
    2019-02-02
  • Briefly explain the simple difference between python2 and python3

    python2: print statement, the statement means that it can be directly followed by the thing to be printed, while the python3: print function, the function thinks that this must be added to brackets before it can be called. The following is a brief introduction to the simple difference between python2 and python3 through this article. Interested friends follow the editor to take a look.
    2018-09-09
  • Detailed analysis of python logging module

    This article mainly introduces the detailed analysis of the python logging module. This article introduces you very detailed through the example code, which has certain reference value for your work or study. Friends who need it can refer to it.
    2020-03-03
  • Python implements a simple ping tool method

    Today, the editor will share with you an article on implementing a simple ping tool for Python, which has good reference value and hope it will be helpful to everyone. Let's take a look with the editor
    2019-01-01
  • Method of drawing stock K-line chart using python numpy+matplotlib

    This article mainly introduces the method of using python numpy+matplotlib to draw a stock K-line chart. The article introduces the example code in detail, which has certain reference learning value for everyone's study or work. Friends who need it, please learn with the editor below.
    2019-06-06
  • Python implements the principle of image cropping through opencv

    This article mainly introduces the analysis of the principle of image cropping through opencv. The article introduces the example code in detail, which has certain reference value for everyone's learning or work. Friends who need it can refer to it
    2020-01-01
  • Can python modify global variables without adding global?

    This article mainly discusses whether python can modify global variables without adding global. We use global variables in the local scope and need to use the global keyword to declare it, otherwise it will not be available. However, the following editor will share with you the modified data types that can be modified inside the function. There is no need to declare global business situation. Friends who need it can refer to it.
    2022-02-02
  • Python implements segmentation and sentence segmentation of Chinese text

    This article mainly introduces in detail how to use Python to implement segmentation and sentence segmentation in Chinese text. Generally speaking, it mainly uses Chinese periods, exclamations, question marks and other symbols. If you are interested, you can learn about it.
    2023-03-03
  • Example of Django adding feeds functionality

    This article mainly introduces examples of Django adding feeds function. The editor thinks it is quite good. I will share it with you now and give you a reference. Let's take a look with the editor
    2018-08-08
  • A brief discussion on the usage of strip(), lstrip() and rstrip() in Python3

    This article mainly introduces a detailed explanation of the usage of strip(), lstrip() and rstrip() in Python 3. The editor thinks it is quite good. I will share it with you now and give you a reference. Let's take a look with the editor
    2019-04-04

Latest Comments