如何在Python Turtle中为随机大小的白色太阳添加发光效果?
实现太阳发光效果的修改方案
要做出类似明亮发光太阳的效果,我们可以通过绘制多层半透明渐变光晕来模拟。下面是修改后的完整代码,保留了你原有的随机大小白色太阳,同时添加了自然的发光效果:
import turtle import random # 初始化基础设置 s = turtle.getscreen() t = turtle.Turtle() t.speed(0) # 最快绘制速度 t.pensize(4) from turtle import Screen, Turtle COLOR = (1, 0.7, 0.06) TARGET = (0.8, 0.09, 0.1) # 绘制日落背景 screen = Screen() screen.tracer(False) screen.setup(width=1.0, height=1.0) WIDTH, HEIGHT = screen.window_width(), screen.window_height() deltas = [(hue - COLOR[index]) / HEIGHT for index, hue in enumerate(TARGET)] bg_turtle = Turtle() bg_turtle.color(COLOR) bg_turtle.penup() bg_turtle.goto(-WIDTH/2, HEIGHT/2) bg_turtle.pendown() direction = 1 for distance, y in enumerate(range(HEIGHT//2, -HEIGHT//2, -1)): bg_turtle.forward(WIDTH * direction) bg_turtle.color([COLOR[i] + delta * distance for i, delta in enumerate(deltas)]) bg_turtle.sety(y) direction *= -1 screen.tracer(True) # 绘制太阳及发光效果 def draw_glow(turtle, center_x, center_y, max_radius): # 从外到内绘制多层半透明光晕,颜色从橙黄渐变到接近白色 glow_colors = [ (1, 0.8, 0.2, 0.1), # 外层淡橙黄,低透明度 (1, 0.9, 0.4, 0.2), (1, 1, 0.6, 0.3), (1, 1, 0.8, 0.4) # 内层接近白,较高透明度 ] # 光晕半径从太阳半径的1.2倍到1.0倍递减 for i, color in enumerate(glow_colors): radius = max_radius * (1.2 - 0.05 * i) turtle.penup() turtle.goto(center_x, center_y - radius) turtle.color(color) turtle.pendown() turtle.begin_fill() turtle.circle(radius) turtle.end_fill() turtle.penup() def Sun(color): t.pu() center_x, center_y = -400, -250 t.goto(center_x, center_y) rad = random.randint(100, 220) # 先画发光光晕,再画中心太阳 draw_glow(t, center_x, center_y, rad) t.color(color) t.pd() t.begin_fill() t.circle(rad) t.end_fill() t.pu() Sun("White") turtle.done()
关键修改说明
- 新增
draw_glow函数:通过4层不同透明度、不同颜色的同心圆,模拟太阳向外扩散的光晕,外层偏橙黄且更透明,内层接近白色且透明度更高,营造自然的发光过渡。 - 调整绘制顺序:先绘制光晕再绘制中心白色太阳,确保光晕在太阳底层,呈现出发光包裹的效果。
- 优化速度与变量:将海龟速度设为
0(最快)避免卡顿,同时修改背景海龟变量名,解决原代码中变量与模块名冲突的问题。
内容的提问来源于stack exchange,提问作者Alec
相关产品推荐
相关产品推荐

