Skip to main content
 首页 » 编程设计

python之如何使用 begin_fill() 分别填充每个花瓣

2024年10月25日10Free-Thinker

我有以下代码可以为我尝试构建的花朵生成花瓣图案。然而,问题是填充部分。

应该发生的是每个花瓣单独填充:

相反,会发生这样的事情:

import turtle 
import math 
 
wn = turtle.Screen() 
wn.bgcolor("white") 
 
def draw_leaf(turtle, side, theta = 0): 
    angle = 2 
    turtle.color("#67bd3c") 
    for x in range(-180,180): 
        y = math.sin(math.radians(angle)) 
        angle += 1 
        y = y * side 
        x_axis = (x % 180) * math.cos(math.radians(theta)) + y * math.sin(math.radians(theta)) 
        y_axis = (x % 180) * (-1 * (math.sin(math.radians(theta)))) + y * math.cos(math.radians(theta)) 
        turtle.goto(-1 * x_axis, -1 * y_axis) 
    return 
 
def draw_flower(turtle, petals): 
    for x in range(petals): 
        theta = 180/(petals - 1) 
        turtle.pendown() 
        turtle.begin_fill() 
        draw_leaf(turtle, 35, theta * x) 
        turtle.end_fill() 
        turtle.penup() 
        turtle.left(theta) 
    return 
 
draw_flower(turtle,4) 
 
wn.exitonclick() 

请您参考如下方法:

看起来每次 draw_leaf 调用都是在 turtle 位于它之前绘制的叶子的远端时开始的。因此,在当前 draw_leaf 期间填充的多边形包括该终点。如果您用不同的颜色绘制每片叶子,这一点会更加明显。

一个可能的解决方案是在您绘制下一片叶子之前,在您的penup 之后转到花的中心。

def draw_flower(turtle, petals): 
    start = turtle.pos() 
    for x in range(petals): 
        theta = 180/(petals - 1) 
        turtle.pendown() 
        turtle.begin_fill() 
        draw_leaf(turtle, 35, theta * x) 
        turtle.end_fill() 
        turtle.penup() 
        turtle.goto(*start) 
        turtle.left(theta) 
    return