【问题标题】:Python Turtle Rectangle Using 2 Corner Coordinates使用 2 个角坐标的 Python Turtle 矩形
【发布时间】:2016-09-08 21:00:00
【问题描述】:

这里是 CS 初学者。我试图让 python 2.7 使用一个函数绘制一个矩形,该函数只有海龟对象、左上角坐标和右下角坐标作为参数。我知道有更简单的绘制矩形的方法,但我试图只使用角坐标。

运行我当前的代码后,我得到以下信息:

TypeError: 不能将序列乘以“float”类型的非整数

我知道这可能很简单,但我无法弄清楚我做错了什么,因此我们将不胜感激。

我的代码如下:

from turtlegraphics import Turtle

def drawLine(t1,x1,y1,x2,y2):
    t1.setWidth(1)
    t1.setColor(0,0,0)
    t1.up()
    t1.move(x1,y1)
    t1.down()
    t1.move(x2,y2)

def rectangleSimple(t2,upperLeftPoint,lowerRightPoint):
    t2.setWidth(1)
    t2.setColor(0,0,0)
    t2.up()
    t2.move(upperLeftPoint)
    t2.down()
    t2.setDirection(270)
    t2.move(lowerRightPoint[2])
    t2.setDirection(0)
    t2.move(lowerRightPoint)
    t2.setDirection(90)
    t2.move(upperLeftPoint[2])
    t2.setDirection(180)
    t2.move(upperLeftPoint)

def main():

    t1 = Turtle()                       
    x1 = 0
    y1 = 0
    x2 = 50
    y2 = 0

    drawLine(t1,x1,y1,x2,y2)

    t2 = Turtle()
    upperLeftPoint = (-100,50)
    lowerRightPoint = (100,-50)

    rectangleSimple(t2,upperLeftPoint,lowerRightPoint)


main()

【问题讨论】:

    标签: python-2.7 turtle-graphics


    【解决方案1】:

    我使用turtle 模块,而不是turtlegraphics,但我猜这两行有问题:

    t2.move(lowerRightPoint[2])
    t2.move(upperLeftPoint[2])
    

    您的 *Point 变量是在索引 0 和 1 处具有两个值 X 和 Y 的元组,但您正在访问索引 2 处不存在的第三个值。有许多不同的方法可以实现您尝试的内容做,这里有一个使用 Python 自带的turtle 模块:

    from turtle import Turtle
    
    X, Y = range(2)
    
    def drawLine(t, x1, y1, x2, y2):
        t.up()
        t.width(1)
        t.pencolor(1, 0, 0)  # red
        t.goto(x1, y1)
        t.down()
        t.goto(x2, y2)
    
    def rectangleSimple(t, upperLeftPoint, lowerRightPoint):
        t.up()
        t.width(1)
        t.pencolor(0, 1, 0)  # green
        t.goto(upperLeftPoint)
        t.setheading(0)  # East
        t.down()
        t.goto(lowerRightPoint[X], upperLeftPoint[Y])
        t.right(90)
        t.goto(lowerRightPoint)
        t.right(90)
        t.goto(upperLeftPoint[X], lowerRightPoint[Y])
        t.right(90)
        t.goto(upperLeftPoint)
    
    if __name__ == "__main__":
    
        from turtle import done
    
        t1 = Turtle()                       
    
        drawLine(t1, 0, 0, 50, 0)
    
        t2 = Turtle()
        upperLeftPoint = (-100, 50)
        lowerRightPoint = (100, -50)
    
        rectangleSimple(t2, upperLeftPoint, lowerRightPoint)
    
        done()
    

    【讨论】:

    • 谢谢你,我很抱歉犯了这样一个基本的错误-_-
    猜你喜欢
    • 2022-01-08
    • 1970-01-01
    • 2018-06-24
    • 1970-01-01
    • 2021-02-15
    • 2021-04-12
    • 1970-01-01
    • 2016-09-22
    • 1970-01-01
    相关资源
    最近更新 更多