Python系列课程:图形库Turtle的使用(一)
Python系列课程:图形库Turtle的使用(二)
Python系列课程:图形库Turtle的使用(三)
关于Turtle的使用,前面我们已经介绍了不少;这张算是一个总结性的文章,自定义一个乘法口诀表;
就直接上代码了,代码里面有详尽的注释
# coding:utf-8
# 引入turtle外部库,turtle是python中一个绘制图像的外部库
import turtle
# 画长方形的画笔
rectangleTurtle = turtle.Turtle();
# 画文字的画笔
fontT = turtle.Turtle();
# 开始绘制的横坐标
startDrawX = -300;
# 开始绘制的纵坐标
startDrawY = 300
# 长方形框
recWidth = 70;
# 长方形框
recHeight = 50;
def iniTurtle():
# 隐藏箭头
fontT.hideturtle();
fontT.penup();
fontT.color('blue')
rectangleTurtle.hideturtle();
rectangleTurtle.penup();
rectangleTurtle.getscreen().screensize(600, 400, "white");
rectangleTurtle.color('black');
rectangleTurtle.goto(startDrawX, startDrawY);
rectangleTurtle.pendown();
#绘制所有的长方形
def drawAllRec():
# 隐藏动画效果
rectangleTurtle.tracer(False);
rectangleTurtle.forward(recWidth * 9);
rectangleTurtle.right(90);
rectangleTurtle.forward(recHeight);
rectangleTurtle.right(90);
rectangleTurtle.forward(recWidth * 9);
rectangleTurtle.right(90);
rectangleTurtle.forward(recHeight);
fontT.goto(startDrawX + 300, startDrawY - 30);
fontT.pendown();
fontT.write("九九乘法口诀表", False, "center");
# 最上面的标题绘制完毕,开始绘制剩下的长方形,剩下的长方形有10条横线和竖线组成
linesSize = 1;
# 绘制完标题之后 ,小乌龟行走的方向朝北,顾需要调整小乌龟的绘制方向,朝东
rectangleTurtle.right(90);
while linesSize <= 10:
rectangleTurtle.penup();
rectangleTurtle.goto(startDrawX, startDrawY - recHeight * linesSize);
rectangleTurtle.pendown();
rectangleTurtle.forward(recWidth * 9);
linesSize = linesSize + 1;
# 恢复默认值
linesSize = 0;
# 改变小乌龟行驶方向,在之前的绘制中,小乌龟绘制方向朝东,顾我们需要让小乌龟朝南绘制
rectangleTurtle.right(90);
# 绘制竖线,x坐标不断+rectangleHeight * linesSize,Y坐标不变
while linesSize <= 9:
rectangleTurtle.penup();
rectangleTurtle.goto(startDrawX + recWidth * linesSize, startDrawY - recHeight);
rectangleTurtle.pendown();
rectangleTurtle.forward(recHeight * 9);
linesSize = linesSize + 1;
# 隐藏动画效果打开动画效果
rectangleTurtle.tracer(True);
#绘制单一的长方形
def drawSingleContents(index):
fontT.tracer(False);
# 乘数
multiplier = index;
# 被乘数
multiplicand = index;
while multiplicand <= 9:
fontT.penup();
# 绘制文字x坐标不变,Y坐标不断缩小
fontT.goto(startDrawX + recHeight / 2 + recWidth * (index - 1), startDrawY - recHeight * multiplicand - 30);
fontT.pendown();
# 整数转字符,并且拼接起来
number = str(multiplier) + "*" + str(multiplicand) + "=" + str(multiplier * multiplicand);
fontT.write(number, False, "center");
multiplicand = multiplicand + 1;
fontT.tracer(True);
def drawAllContents():
index = 1;
while index <= 9:
drawSingleContents(index);
index = index + 1;
iniTurtle();
drawAllRec();
drawAllContents();
turtle.done();