Create a Myanmar Flag With Python Turtle

I recently embarked on a fun coding project to recreate the Myanmar flag using Python. As I progressed, I realized there were numerous ways to enhance the functionality and make the project more dynamic, user-friendly, and practical. In this blog, I’ll walk you through the process, the enhancements I made, and how you can recreate and customize this project yourself.

Draw the Myanmar Flag

The Myanmar flag consists of three horizontal stripes (yellow, green, and red) and a central white star. To create it programmatically, I used Python’s matplotlib library for visualization and numpy for calculations.

Here’s the initial code snippet to draw the flag:

import matplotlib.pyplot as plt
from matplotlib.patches import Polygon
import numpy as np

def draw_myanmar_flag(flag_width=8, flag_height=5, save_path=None, show_grid=False, title="Myanmar Flag"):
    """
    Function to draw the Myanmar flag with optional customization.
    :param flag_width: Width of the flag.
    :param flag_height: Height of the flag.
    :param save_path: File path to save the flag image. If None, the flag is not saved.
    :param show_grid: Boolean to display gridlines for debugging.
    :param title: Title to display above the flag.
    """
    # Create the figure and axis
    fig, ax = plt.subplots(figsize=(flag_width, flag_height))

    # Draw the three stripes
    ax.fill_between([0, 3], 2, 3, color="#FFD100")  # Yellow stripe
    ax.fill_between([0, 3], 1, 2, color="#34B233")  # Green stripe
    ax.fill_between([0, 3], 0, 1, color="#EA2839")  # Red stripe

    def draw_star(center_x, center_y, radius, color, rotation_deg):
        """
        Function to draw a star with the given parameters.
        :param center_x: X-coordinate of the star center.
        :param center_y: Y-coordinate of the star center.
        :param radius: Outer radius of the star.
        :param color: Color of the star.
        :param rotation_deg: Rotation angle of the star in degrees.
        """
        points = []
        for i in range(10):
            angle = (i * 36 + rotation_deg) * (np.pi / 180)
            r = radius if i % 2 == 0 else radius / 2
            x = center_x + r * np.cos(angle)
            y = center_y + r * np.sin(angle)
            points.append((x, y))
        polygon = Polygon(points, closed=True, color=color)
        ax.add_patch(polygon)

    # Draw the central star
    draw_star(1.5, 1.5, 0.6, "white", rotation_deg=55)

    # Set axis limits and aesthetics
    ax.set_xlim(0, 3)
    ax.set_ylim(0, 3)
    ax.axis("off")  # Hide the axis

    # Add gridlines if enabled
    if show_grid:
        ax.grid(color='gray', linestyle='--', linewidth=0.5)

    # Add a title
    plt.title(title, fontsize=16, weight='bold', pad=20)

    # Show the flag
    plt.show()

    # Save the flag image if a save path is specified
    if save_path:
        fig.savefig(save_path, dpi=300, bbox_inches='tight')
        print(f"Flag saved at {save_path}")

# Customize and call the function
draw_myanmar_flag(
    flag_width=10,
    flag_height=6,
    save_path="myanmar_flag.png",
    show_grid=True,
    title="Happy Independence Day Myanmar!"
)

Taking the Project Further:

While the basic implementation works well, I wanted to add more functionality to make the project more versatile and engaging. Here are the enhancements I introduced:

  1. Dynamic Inputs:
    • Users can now customize the flag’s dimensions, colors, star size, and rotation angle.
    • This allows for greater flexibility, making the script adaptable for different screen sizes or design preferences.
  2. Save Option:
    • Added functionality to save the flag as a PNG file.
    • This is particularly useful if you want to reuse the flag image in presentations or projects.
  3. Improved Star Drawing:
    • The star’s points are dynamically calculated based on the center coordinates, radius, and rotation angle provided by the user.
    • This ensures accuracy and makes it easy to modify the star’s appearance.
  4. Optional Gridlines:
    • I included a gridline option for better visualization. This is useful when debugging or aligning elements.
  5. Title Customization:
    • You can specify a custom title to display above the flag, making it suitable for different occasions or themes.

How to Run the Script:

  1. Set Up Your Environment:
    • Make sure you have Python installed along with the matplotlib and numpy libraries. You can install these using pip:pip install matplotlib numpy
  2. Copy and Paste the Code:
    • Copy the enhanced script above into your Python IDE or Jupyter Notebook.
  3. Customize the Parameters:
    • Modify the parameters in the draw_myanmar_flag function to suit your needs:
      • flag_width and flag_height for dimensions.
      • save_path to specify where the PNG file should be saved.
      • show_grid to toggle gridlines.
      • title to set a custom title.
  4. Run the Script:
    • Execute the script to generate the flag.
    • If you specified a save_path, check your directory for the saved image.

Output:

Running the script with the following parameters:

draw_myanmar_flag(
    flag_width=10,
    flag_height=6,
    save_path="myanmar_flag.png",
    show_grid=True,
    title="Happy Independence Day Myanmar!"
)
  • A large, vibrant Myanmar flag with gridlines for debugging.
  • The flag image saved as myanmar_flag.png in the specified directory.
  • A bold title displayed above the flag.

Conclusion

This project was a fun way to combine programming with creativity. By enhancing the functionality, I’ve turned a simple visualization into a dynamic tool that can be customized for various needs. Whether you’re a beginner looking to learn Python or an advanced coder seeking inspiration, this project offers a great balance of simplicity and versatility.

Feel free to try it out, customize it, and share your creations. Let me know in the comments how you used this project or what enhancements you’d like to see next!

Related blog posts