![](/img/trans.png)
[英]How do I draw a circle looping around with a circle in the middle at the end using python turtle?
[英]How do I draw polygons around a center point in python turtle
我想定義這個函數,以便用戶可以輸入任意數量的邊、長度和坐標。 我面臨的問題是我希望坐標是多邊形的中心,而不是角落,但我不確定如何。 下面是我當前的代碼
import turtle
WIDTH,HEIGHT= 1200,700
screen = turtle.Screen()
screen.setup(WIDTH,HEIGHT)
def draw_polygon(x,y,sides,length):
pen=turtle.Turtle()
pen.hideturtle()
pen.speed(-1)
pen.penup()
pen.setpos(x,y)
pen.pendown()
for i in range (0,sides):
pen.fd(length)
pen.right(360/sides)
while True:
s=int(input())
l=int(input())
draw_polygon(0,0,s,l)
海龜從它的設置位置開始繪制,因為你是順時針繪制的,這意味着給定的位置將始終是多邊形的左上角。 要使您傳遞給函數的位置成為中心,您必須偏移海龜的起始位置。
x 軸上的偏移將始終是一側長度的一半,當多邊形接近圓時接近零。
y 軸上的偏移量將是多邊形的半徑。
在您的代碼中,替換您設置的位置以相應地偏移海龜的起始位置。
from math import pi
startPosX = x - length/2
startPosY = y + length * sides / (2*pi)
pen.setpos(startPosX,startPosY)
在旁注中,您可以添加:
turtle.Screen().exitonclick()
在 drawPolygon() 的末尾而不是 while 循環中,以在您輸入值后保持屏幕亮起。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.