在这里开始CS学生。我试图让python 2.7使用一个只有乌龟对象,左上角坐标和右下角坐标作为参数的函数绘制一个矩形。我知道绘制矩形有更简单的方法,但我只是尝试使用角坐标。
运行我当前的代码后,我得到以下内容:
TypeError:不能将序列乘以'float'
类型的非int我知道这可能很简单,但我无法弄清楚我做错了什么,所以任何帮助都会受到赞赏。
我的代码如下:
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()
答案 0 :(得分:0)
我使用的是turtle
模块,而不是turtlegraphics
,但我的猜测是这两行存在问题:
t2.move(lowerRightPoint[2])
t2.move(upperLeftPoint[2])
你的* Point变量是带有两个值的元组,X& Y,索引0& 1但你正在访问索引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()