Python Turtle图形比例大小和位置

标签 python turtle-graphics

我需要一些有关 Python turtle 图形的帮助。我需要创建一个在 for ... in range() 循环中每次变小的房子。

我正在用三座由基本 turtle 形状组成的房子来创作风景。有没有办法,当我创建具有基本形状的房子时,我可以使用 for ... in range() 循环来更改房子位置并使其尺寸小一点?

到目前为止我正在尝试:

def house(turtlename,hs,xroof,xdoor,xwindow,ywindow):
 housesquare(turtlename,hs)
 turtlename.pu()
 turtlename.goto ((int(hs*xroof),int(hs*1)))
 turtlename.pd()
 housetriangle(turtlename,hs)
 turtlename.pu()
 turtlename.goto((int(hs*xdoor),0 ))
 turtlename.pd()
 housedoor(turtlename,hs*0.7,hs*0.3)
 turtlename.pu()
 turtlename.goto((int(hs*xwindow), int(hs*ywindow)))
 turtlename.pd()
 housesquare(turtlename,hs*0.3)

使用这段代码,我尝试绘制第二个尺寸较小的房子。 goto() 命令会扰乱整个形状,我必须手动完成所有操作,但任务是使用 for ... in range(4) 来绘制四个房子,每个都较小并放置在稍远的距离。

最佳答案

您需要绘制相对时尚,而不是绝对时尚。您可以使用 .goto() 来完成此操作,它通常看起来像:

turtle.goto(turtle.xcor() + hs * xwindow, turtle.ycor() + hs * ywindow)

也就是说,相对于你现在所在的位置移动。但是,完全避免 .goto() 并使用 .forward().backward() 等相对运动方法可能会更简单、.left()、&.right()。以下是使用这些相对运动方法对代码进行的修改:

from turtle import Turtle, Screen

def housesquare(turtle, width):
    for _ in range(4):
        turtle.forward(width)
        turtle.left(90)

def housetriangle(turtle, base):
    for _ in range(3):
        turtle.forward(base)
        turtle.left(120)

def housedoor(turtle, height, width):
    for _ in range(2):
        turtle.forward(width)
        turtle.left(90)
        turtle.forward(height)
        turtle.left(90)

def house(turtle, hs, xroof, xdoor, xwindow, ywindow):
    housesquare(turtle, hs)

    turtle.penup()
    turtle.left(90)
    turtle.forward(hs)
    turtle.right(90)
    turtle.forward(hs * xroof)
    turtle.pendown()
    housetriangle(turtle, hs)

    turtle.penup()
    turtle.right(90)
    turtle.forward(hs)
    turtle.left(90)
    turtle.forward(hs * xdoor)
    turtle.pendown()
    housedoor(turtle, hs * 0.7, hs * 0.3)

    turtle.penup()
    turtle.backward(hs * xdoor)
    turtle.forward(hs * xwindow)
    turtle.left(90)
    turtle.forward(hs * ywindow)
    turtle.right(90)
    turtle.pendown()
    housesquare(turtle, hs * 0.3)

    turtle.penup()
    turtle.backward(hs * xwindow)
    turtle.left(90)
    turtle.backward(hs * ywindow)
    turtle.right(90)
    turtle.pendown()

screen = Screen()
yertle = Turtle()

size = 100

for factor in range(1, 4):

    house(yertle, size / factor, 0.0, 0.2, 0.6, 0.4)

    yertle.penup()
    yertle.forward(1.5 * size / factor)
    yertle.right(15)
    yertle.pendown()

yertle.hideturtle()

screen.exitonclick()

请注意,由于相对的绘制逻辑,它不仅可以绘制不同尺寸的房子,还可以旋转它:

enter image description here

关于Python Turtle图形比例大小和位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49487533/

相关文章:

python - 根据方向键移动 turtle

python - 将图表与 turtle 模块制作的绘图结合起来

python - 使用 python 将多行导入具有唯一约束的 SQL 表

python - 时间戳传递给 matplotlib.date2num : 'str' object has no attribute 'toordinal'

python - turtle 图形无响应

Python Turtle 在包含框中写入值

python - MySQL连接器无法正常工作并给出错误

Python对数之间的取模

python - 清理用户输入以包含在 href 属性中?

python - Turtle 模块 - 保存图像