Fundamentals 3 min read

Drawing a Starry Sky with Python Turtle

This tutorial demonstrates how to use Python's turtle module to randomly generate and draw a starry sky, explaining the core logic of random positions, sizes, and angles for each star and providing complete code to render the night sky effect.

Python Programming Learning Circle
Python Programming Learning Circle
Python Programming Learning Circle
Drawing a Starry Sky with Python Turtle

This article teaches how to create a starry night scene using Python's turtle graphics library. It outlines the basic approach: placing stars at random canvas coordinates, assigning each a random size, and rotating them by random angles to achieve a natural look.

Key steps :

Stars appear at random positions on the canvas.

Each star has a random size.

Stars are drawn with random tilt angles.

The following code implements the described logic. It defines a star function that draws a single five‑pointed star, then loops to place multiple stars with random parameters.

<code>import turtle as t
from random import randint

def star(x,y,size,angle): #定义函数,绘制星星
    t.color('yellow')#设置星星的颜色
    t.pu()
    t.setpos(x,y)
    t.right(angle)
    t.begin_fill()#调用开始填充函数
    for i in range(5):#循环绘制五角星
        t.fd(size)
        t.left(72)
        t.fd(size)
        t.right(144)
    t.end_fill()#调用结束填充函数

t.TurtleScreen._RUNNING=True
t.setup(1000,800)#设置画布大小
t.hideturtle()#隐藏小海龟
t.speed(0) #设置画笔绘画速度
t.pensize(1)#设置画笔宽度
t.bgcolor('black') #设置画布背景颜色为黑色,星星要在黑夜里发光
t.pu()
for i in range(150):#循环绘制星星数量
    x=randint(-400,400)#星星的横坐标范围
    y=randint(-300, 300)#纵坐标范围
    s=randint(1,5)#设置星星大小范围
    a=randint(0,120)#角度范围
    star(x, y, s, a)#调用函数绘制星星
t.done()</code>

Running the script produces a black canvas dotted with yellow stars of varying sizes and orientations, resembling a night sky.

graphicstutorialturtleRandomstarfield
Python Programming Learning Circle
Written by

Python Programming Learning Circle

A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.