Python Turtle全屏背景开发:中央太阳与棕榈树剪影绘制求助
实现带中央太阳与棕榈树剪影的全屏背景(基于Python Turtle)
你当前的代码仅绘制了局部渐变条,且未添加棕榈树剪影。以下是完善后的实现,覆盖全屏渐变背景、中央太阳和两侧棕榈树剪影:
关键改进点
- 全屏渐变背景:获取屏幕实际尺寸,遍历整个高度绘制水平渐变条,覆盖全屏宽度
- 棕榈树剪影绘制:通过自定义函数绘制黑色填充的棕榈树轮廓,包含树干和树叶
- 层级优化:按「背景渐变→太阳→剪影」的顺序绘制,确保视觉层级符合原图效果
完整代码
import turtle # 初始化全屏屏幕 screen = turtle.Screen() screen.setup(width=1.0, height=1.0) screen.bgcolor("black") # 初始深色背景避免绘制闪烁 screen.tracer(0) # 关闭实时动画加速绘制 turtle.speed(0) turtle.colormode(255) turtle.hideturtle() # 获取屏幕尺寸参数 screen_width = screen.window_width() screen_height = screen.window_height() half_width = screen_width // 2 half_height = screen_height // 2 # 绘制上部渐变:蓝紫色过渡到粉紫色 for y in range(half_height, 0, -1): ratio = (half_height - y) / half_height r = int(154 + 67 * ratio) g = int(0 + 67 * ratio) b = int(254 - 67 * ratio) turtle.color(r, g, b) turtle.penup() turtle.goto(-half_width, y) turtle.pendown() turtle.goto(half_width, y) # 绘制中部渐变:粉紫色过渡到橙红色 for y in range(0, -half_height // 2, -1): ratio = abs(y) / (half_height // 2) r = 221 g = int(67 + 55 * ratio) b = int(187 - 55 * ratio) turtle.color(r, g, b) turtle.penup() turtle.goto(-half_width, y) turtle.pendown() turtle.goto(half_width, y) # 绘制下部渐变:橙红色过渡到深褐色 for y in range(-half_height // 2, -half_height, -1): ratio = (abs(y) - half_height // 2) / (half_height // 2) r = 221 g = 122 b = int(132 - 52 * ratio) turtle.color(r, g, b) turtle.penup() turtle.goto(-half_width, y) turtle.pendown() turtle.goto(half_width, y) # 绘制中央黄色太阳 turtle.penup() turtle.goto(0, -100) # 调整位置让太阳垂直居中 turtle.pendown() turtle.fillcolor("yellow") turtle.begin_fill() turtle.circle(100) turtle.end_fill() # 自定义棕榈树绘制函数 def draw_palm_tree(x, y): turtle.penup() turtle.goto(x, y) turtle.pendown() turtle.fillcolor("black") turtle.begin_fill() # 绘制树干 for _ in range(2): turtle.forward(30) turtle.left(90) turtle.forward(150) turtle.left(90) # 绘制三组树叶 turtle.penup() turtle.goto(x + 15, y + 150) turtle.pendown() turtle.setheading(90) for _ in range(3): turtle.left(120) turtle.forward(100) turtle.left(120) turtle.forward(100) turtle.left(120) turtle.forward(100) turtle.right(60) turtle.end_fill() # 绘制左右两侧的棕榈树剪影 draw_palm_tree(-half_width + 80, -half_height + 20) draw_palm_tree(half_width - 110, -half_height + 20) screen.update() # 一次性更新屏幕显示 turtle.done()
细节说明
- 使用
screen.tracer(0)关闭实时动画,配合screen.update()批量刷新,大幅提升渐变背景的绘制速度 - 渐变色彩参数完全匹配你提供的原图过渡规律
- 棕榈树采用黑色填充实现剪影效果,位置固定在屏幕左右下角,贴合原图布局
内容的提问来源于stack exchange,提问作者Louis Lam
相关产品推荐
相关产品推荐

