How to draw a triangle in Python
Learn how to draw a triangle in Python. This guide covers different methods, tips, real-world applications, and how to debug common errors.
.png)
Python offers a great way to learn the basics of graphics when you draw a triangle. Its libraries make the creation of geometric shapes simple with just a few lines of code.
In this article, you'll find techniques, practical tips, and real-world applications. You'll also get advice to debug your code and select the best approach for any project.
Using the turtle module for basic triangle
import turtle
t = turtle.Turtle()
for _ in range(3):
t.forward(100)
t.left(120)
turtle.done()--OUTPUT--# Output: A window appears with a triangle drawn by the turtle
The turtle module offers a simple way to create graphics by guiding a virtual pen. This code uses a for loop to efficiently draw the triangle's three equal sides without repeating code.
- The
t.forward(100)command draws each side 100 pixels long. - The
t.left(120)command turns the pen. You use 120 degrees because it's the exterior angle required to create a closed equilateral shape—360 degrees divided by three sides.
Graphical approaches to triangle drawing
Beyond the turtle module's visual simplicity, you can also render triangles with powerful plotting libraries, interactive toolkits, or even simple text-based ASCII art.
Using matplotlib to plot a triangle
import matplotlib.pyplot as plt
import numpy as np
x = np.array([0, 1, 2, 0])
y = np.array([0, 2, 0, 0])
plt.plot(x, y)
plt.show()--OUTPUT--# Output: A window appears with a triangle displayed in a graph
The matplotlib library creates visualizations by plotting data points. In this approach, you define the triangle’s vertices using two NumPy arrays for the x and y coordinates. The library then connects these points to render the shape.
- The
xandyarrays store the coordinates for each vertex. The points are (0,0), (1,2), and (2,0). - Notice the starting coordinate is repeated at the end of each array. This ensures the shape is closed.
- Finally,
plt.plot()connects the vertices, andplt.show()displays the resulting graph.
Creating ASCII art triangles with loops
def print_triangle(height):
for i in range(height):
print(' ' * (height - i - 1) + '*' * (2 * i + 1))
print_triangle(5)--OUTPUT--*
***
*****
*******
*********
This approach builds a text-based triangle using a simple loop. The print_triangle function iterates from the top down, printing one row at a time. Inside the loop, string multiplication and concatenation construct each line before it’s printed to the console.
- The expression
' ' * (height - i - 1)calculates the necessary leading spaces to indent each row correctly. - Then,
'*' * (2 * i + 1)determines the number of asterisks, ensuring each new row grows wider by two stars.
Using tkinter for interactive triangle drawing
import tkinter as tk
root = tk.Tk()
canvas = tk.Canvas(root, width=300, height=200)
canvas.pack()
canvas.create_polygon(150, 50, 100, 150, 200, 150, fill="blue")
root.mainloop()--OUTPUT--# Output: A window appears with a blue triangle
The tkinter library is Python's standard toolkit for building graphical user interfaces. This approach creates a main window and adds a Canvas widget, which gives you a space to draw shapes. The root.mainloop() call starts the application's event loop, making the window interactive and responsive to user input.
- The
canvas.create_polygon()function draws the shape by connecting a series of points. - You define the triangle’s vertices by passing their coordinates—(150, 50), (100, 150), and (200, 150)—as arguments.
- The
fill="blue"parameter colors the resulting polygon.
Advanced triangle techniques
As your projects grow more complex, you'll find that specialized libraries offer more power for image processing, game development, and computer vision.
Creating triangles with the PIL library
from PIL import Image, ImageDraw
img = Image.new('RGB', (400, 300), color='white')
draw = ImageDraw.Draw(img)
draw.polygon([(200, 50), (100, 250), (300, 250)], fill='green')
img.show()--OUTPUT--# Output: An image window appears with a green triangle
The PIL library, also known as Pillow, is a powerful tool for image manipulation. The process starts by creating a blank canvas with Image.new(), where you specify the image mode, dimensions, and background color. This gives you a fresh image to work on.
- An
ImageDrawobject acts as your drawing tool, allowing you to add shapes to the image you just created. - The
draw.polygon()function renders the triangle by connecting the coordinates you provide in a list. Thefillparameter lets you set the shape's color.
Building triangles with pygame
import pygame
pygame.init()
screen = pygame.display.set_mode((400, 300))
pygame.draw.polygon(screen, (255, 0, 0), [(200, 50), (100, 250), (300, 250)])
pygame.display.flip()
pygame.time.wait(3000) # Display for 3 seconds--OUTPUT--# Output: A pygame window appears with a red triangle
The pygame library is a go-to for creating games and interactive applications. It works by setting up a display window, which acts as a canvas where you can draw shapes. This approach gives you direct control over rendering—essential for dynamic graphics.
- The
pygame.draw.polygon()function does the heavy lifting. You give it the screen to draw on, a color as an RGB tuple like(255, 0, 0)for red, and a list of coordinates for the triangle's vertices. - After drawing, you must call
pygame.display.flip()to update the screen and make your triangle visible.
Precision triangle drawing with OpenCV
import cv2
import numpy as np
img = np.zeros((300, 400, 3), dtype=np.uint8)
img.fill(255) # White background
vertices = np.array([[200, 50], [100, 250], [300, 250]], np.int32)
cv2.fillPoly(img, [vertices], (0, 255, 0)) # Green filled triangle
cv2.imshow('Triangle', img)
cv2.waitKey(0)--OUTPUT--# Output: An OpenCV window appears with a green filled triangle
The OpenCV library is a powerhouse for computer vision, treating images as NumPy arrays for pixel-level manipulation. This code starts by creating a blank white image as a NumPy array. It then defines the triangle's vertices in a separate array with a specific integer data type that OpenCV requires.
- The
cv2.fillPoly()function renders the shape. It uses the vertex coordinates to draw a filled polygon directly onto the image array with a specified color. - Finally,
cv2.imshow()displays the image in a window, whilecv2.waitKey(0)pauses the script to keep the window open until you press a key.
Move faster with Replit
Replit is an AI-powered development platform that transforms natural language into working applications. Describe what you want to build, and Replit Agent creates it—complete with databases, APIs, and deployment.
For the triangle-drawing techniques we've explored, Replit Agent can turn them into production tools:
- Build an interactive geometry tool that visualizes triangles from user-defined coordinates using
tkinterorpygame. - Create a simple game asset generator that exports triangular shapes as image files with
PIL. - Deploy a data visualization dashboard that uses
matplotlibto plot triangular relationships between data points.
Describe your app idea, and Replit Agent can write the code, test it, and handle deployment automatically.
Common errors and challenges
Even simple triangle-drawing code can have tricky bugs, but a few common fixes will get your shapes rendering correctly.
- Fixing the
turtlescreen that closes immediately: If yourturtlewindow vanishes as soon as it appears, it’s because the script finished running. You need to tell it to wait. Addingturtle.done()orturtle.exitonclick()at the end of your script keeps the window open until you close it manually. - Troubleshooting unclosed triangles in
matplotlib: A common mistake inmatplotlibis getting a two-sided line instead of a closed triangle. This happens when you don't tell the library to connect the last vertex back to the first. To fix this, make sure the starting coordinate is also the final coordinate in yourxandyarrays. - Correcting misaligned ASCII art triangles: When your text-based triangle looks skewed or lopsided, the issue is usually in the loop's math. Double-check the formulas that calculate the leading spaces and the number of asterisks. A small error in expressions like
' ' * (height - i - 1)or'*' * (2 * i + 1)can throw off the entire shape's alignment.
Fixing the turtle screen that closes immediately
It’s a common hiccup for beginners: you run your turtle script, a window flashes on the screen, and then it’s gone. The code works, but the program finishes so quickly that you can't see the result. The following example demonstrates this.
import turtle
t = turtle.Turtle()
for _ in range(3):
t.forward(100)
t.left(120)
# Window closes immediately after drawing the triangle
Because the script has no command to pause after drawing, the program closes the window the moment it finishes. The corrected code below shows how a single instruction can solve this and keep the result on screen.
import turtle
t = turtle.Turtle()
for _ in range(3):
t.forward(100)
t.left(120)
turtle.done() # Keeps the window open until manually closed
The fix is to add turtle.done() at the end of your script. This function starts an event loop that keeps the graphics window open until you manually close it. Without this command, the script finishes its drawing task and immediately exits, causing the window to disappear. You'll run into this common issue whenever a script's main purpose is to draw a shape and then stop, so it's a good habit to include it.
Troubleshooting unclosed triangles in matplotlib
In matplotlib, it's common to get a two-sided line instead of a closed triangle. The plt.plot() function connects vertices in order but won't automatically close the shape for you. The following code demonstrates this common oversight.
import matplotlib.pyplot as plt
import numpy as np
x = np.array([0, 1, 2])
y = np.array([0, 2, 0])
plt.plot(x, y)
plt.show()
Because the coordinate arrays only contain three points, plt.plot() draws two connected lines but has no instruction to connect the final point back to the origin. The corrected code below shows how to complete the figure.
import matplotlib.pyplot as plt
import numpy as np
x = np.array([0, 1, 2, 0]) # Add first point again to close the triangle
y = np.array([0, 2, 0, 0])
plt.plot(x, y)
plt.show()
The fix is to repeat the starting coordinate at the end of your x and y arrays. The plt.plot() function connects vertices in the order they appear, so it needs an explicit instruction to draw the final line segment back to the origin. This is a key detail to remember whenever you're plotting any closed polygon, as the library won't automatically complete the shape for you.
Correcting misaligned ASCII art triangles
When your text-based triangle looks skewed, the issue is usually in the loop's math. Without the correct formula for leading spaces, the shape won't be centered. The following code shows what happens when only the asterisks are printed.
def print_triangle(height):
for i in range(height):
print('*' * (i + 1))
print_triangle(5)
This code produces a right-angled triangle because print('*' * (i + 1)) only grows the number of asterisks. Since each line starts at the same position, the shape isn't symmetrical. The corrected code below addresses this.
def print_triangle(height):
for i in range(height):
print(' ' * (height - i - 1) + '*' * (2 * i + 1))
print_triangle(5)
The fix centers the triangle by adding leading spaces before the asterisks on each line. The expression ' ' * (height - i - 1) calculates the correct indentation, pushing each row to the right. Meanwhile, '*' * (2 * i + 1) ensures each line grows by two stars, creating a symmetrical shape. This kind of alignment math is crucial for any text-based procedural art where positioning is key.
Real-world applications
Now that you can draw and debug triangles, you can apply these skills to build practical tools like compasses and 3D terrain models.
Creating a directional compass with turtle triangles
The turtle module can draw a filled, isosceles triangle to serve as a simple compass needle, using the shape’s point to indicate a direction like North.
import turtle
t = turtle.Turtle()
t.fillcolor("red")
t.begin_fill()
t.setheading(90) # Point North
for i in range(3):
t.forward(80 if i == 0 else 50)
t.right(120)
t.end_fill()
turtle.done()
This code uses turtle to draw a filled, red shape. The process starts by setting the fill color with t.fillcolor("red") and then calling t.begin_fill() to start recording the shape's outline. The turtle's orientation is first set to point upward using t.setheading(90).
Then, a for loop draws the shape's three sides:
- A conditional statement,
t.forward(80 if i == 0 else 50), makes the first side longer than the other two. - The
t.right(120)command turns the turtle after drawing each side. - Finally,
t.end_fill()completes the shape by connecting the endpoint to the start and filling it with color.
Generating 3D terrain models with triangular meshes
Triangular meshes are fundamental to 3D graphics, and you can use matplotlib to create your own by connecting a set of 3D points to form a terrain-like surface.
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.tri import Triangulation
x, y = np.random.rand(2, 20)
z = 0.3 * (x**2 + y**2) # Height function
tri = Triangulation(x, y)
ax = plt.figure().add_subplot(111, projection='3d')
ax.plot_trisurf(x, y, z, triangles=tri.triangles, cmap='terrain')
plt.show()
This code builds a 3D plot from scratch. It starts by generating 20 random x and y coordinates and then calculates a corresponding z height for each pair to create a curved surface.
- The key is the
Triangulationclass, which intelligently maps out how to connect all thexandypoints into a network of triangles. - Then,
ax.plot_trisurftakes these coordinates and the triangle map to draw the final 3D surface, coloring it with the'terrain'colormap.
Get started with Replit
Put these techniques into practice with Replit Agent. Describe a tool, like “a tkinter app to visualize a triangle from side lengths,” or “a PIL script to generate random triangle assets.”
The agent writes the code, tests for errors, and deploys your application. Start building with Replit and bring your ideas to life.
Create and deploy websites, automations, internal tools, data pipelines and more in any programming language without setup, downloads or extra tools. All in a single cloud workspace with AI built in.
Create & deploy websites, automations, internal tools, data pipelines and more in any programming language without setup, downloads or extra tools. All in a single cloud workspace with AI built in.


.png)
.png)