【问题标题】:How can I make the turtle function calculate the total length value drawn?如何让海龟函数计算绘制的总长度值?
【发布时间】:2021-05-11 13:55:55
【问题描述】:

所以我需要我的乌龟在用户点击屏幕的位置绘制任何正多边形 并打印出他们绘制的多边形的总长度。

import turtle
t=turtle.Turtle()
tlength=0

def figure(num, length):       
    for i in range(num):
        t.forward(length)
        t.left(360/num)
        global tlength
        tlength = tlength+length

        
def drawit(x, y):              
    shape = int(turtle.textinput("","What Shape?"))

    if shape!="0":
        length = int(turtle.textinput("","The length of side? "))
       
    
    t.penup()
    t.goto(x, y)
    t.pendown()
    figure(shape, length)
    t.write("total drawn length=", tlength)

s = turtle.Screen()
s.onscreenclick(drawit)

这是我到目前为止所拥有的......它运作良好,只是它不会打印出总长度。有什么建议吗?

【问题讨论】:

  • 你能修正你的代码格式吗?否则很难理解您的代码。
  • 你为什么不用t.xcor()

标签: python python-3.x turtle-graphics python-turtle


【解决方案1】:

你有一些代码问题:

t.write("total drawn length=", tlength)

这不起作用,因为write() 不需要显示多个参数,而是只显示一个。检查文档。

shape = int(...)

if shape != "0":

您只是将shape 强制为int,然后测试它是否不是字符串——这总是正确的。此外,如果用户点击“取消”并且textinput() 返回Noneint() 调用将失败。

tlength=0

这只会初始化一次,因此任何后续多边形都会将前面多边形的周长添加到它们的总长度中。

以下是您的程序的返工,它修复了上述大部分问题并且基本上可以正常工作:

from turtle import Screen, Turtle

def figure(sides, length):
    perimeter = 0

    for _ in range(sides):
        turtle.forward(length)
        perimeter += length

        turtle.left(360 / sides)

    return perimeter

def drawit(x, y):
    shape = screen.textinput("", "How many sides?")

    if not shape:
        return

    length = screen.textinput("", "The length of one side?")

    if not length:
        return

    turtle.penup()
    turtle.goto(x, y)
    turtle.pendown()

    total_length = figure(int(shape), int(length))
    turtle.write("Total drawn length = " + str(total_length))

turtle = Turtle()
turtle.hideturtle()

screen = Screen()
screen.onscreenclick(drawit)
screen.mainloop()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-05
    • 1970-01-01
    • 1970-01-01
    • 2012-11-23
    • 1970-01-01
    相关资源
    最近更新 更多