python :turtle画笔设置函数

tech2022-08-15  147

python :turtle画笔设置函数

turtle英⽂是“乌⻳的意思”,当我们使⽤turtle时,想象⼀只⼩乌⻳在⼀个横轴为x、纵轴为y的坐标系原点(0,0),它爬过的路线形成线条。那我们可以对“⼩乌⻳”(画笔)本身进⾏⼀些设置:

函数 描述 : 初始化画布 (这里只提供了turtle的一些基本设置函数,更多函数请自行百度) turtle.penup() 提起画笔,海⻳⻜行不留下痕迹 turtle.pendown() 放下画笔,海⻳爬行留下痕迹 turtle.pencolor(color) 海⻳的涂装,可以为字符串或RGB三元组 turtle.pensize(width) 画笔宽度,海⻳的腰围 turtle.setup(width,height,startx,starty) 创建画布,weidth:画布宽度,height:画布高度,(startx,starty)表示矩形窗口左上角顶点 的位置 turtle.screensize(canvwidth=None,convheight=None,bg=None) 设置画布大小,参数分别为画布的宽(单位像素),高,背景颜色 turtle.colormode(mode) 设置颜色模式,默认小数模式,255大数模式

函数 描述 : 画图操作 turtle.forward(x) 向当前画笔⽅向移动x个像素 turtle.backward(x) 向当前画笔相反⽅向移动x像素⻓度 turtle.left(degree) 当前⽅向左转degree度,只转向不移动 turtle.right(degree) 当前⽅向右转degree度,只转向不移动 turtle.circle(radius,extent=None) 根据半径radius绘制extent⻆度的弧形,默认为360

注:坐标系就是以海⻳(画笔)的出⽣点为原点(0,0),以像素为单位将整个画布做出划分,使用goto()可以到达画布任何位置

**示例一:**画出一个正方体:

import turtle import turtle as t t.setup(400,400) #创建画布 t.screensize(400,400,"yellow") #设置画布 大小:400*400 ,颜色:黄色 t.pensize(15) #设置画笔大小 t.pencolor("red") #设置画笔颜色 :红色 t.penup() #抬起画笔 t.goto(100,100) #将画笔移动到指定坐标(x,y)(100,100) t.pendown() #放下画笔 (放下即可开始画图) t.goto(-100,100) t.goto(-100,-100) t.goto(100,-100) t.goto(100,100) t.goto(140,140) t.goto(-60,140) t.goto(-100,100) t.penup() t.goto(100,-100) t.pendown() t.goto(140,-60) t.goto(140,140) t.penup() t.goto(-100,-100) t.pendown() t.goto(-60,-60) t.goto(140,-60) t.penup() t.goto(-60, -60) t.pendown() t.goto(-60, 140) t.done() #用来停止画笔绘制,但绘图窗体不关闭

**示例二:**绘制数码管:

import turtle import turtle as t def DrawInit(): #初始化画布 t.screensize(400, 400, "yellow") #400 * 400大小 黄色 t.pensize(15) t.pencolor("red") t.penup() t.goto(-130, 0) return def IsDrawLine(condition = True): #画出长40一划 t.pendown() if condition else t.penup() t.forward(40) #向当前画笔⽅向移动40个像素 return def IsDrawColon(): #划出冒号 " : " t.left(90) #画笔往左旋转90度 t.forward(15) t.pendown() t.forward(5) t.penup() t.left(180) t.forward(30) t.pendown() t.forward(5) t.penup() t.left(180) t.forward(20) t.right(90) return def DrawNum(num): # 画出数字 共7划 IsDrawLine(True) if num in [2,3,4,5,6,8,9] else IsDrawLine(False) # 第一划 t.left(90) #2 IsDrawLine(True) if num in [0,2,3,4,7,8,9] else IsDrawLine(False) #第二划 t.left(90) IsDrawLine(True) if num in [0,2,3,5,6,7,8,9] else IsDrawLine(False) t.left(90) IsDrawLine(True) if num in [0, 1, 4, 5, 6, 8, 9] else IsDrawLine(False) # 4 IsDrawLine(True) if num in [0,1,2,6,8] else IsDrawLine(False) # 5 t.left(90) IsDrawLine(True) if num in [0,2, 3, 5, 6, 8, 9] else IsDrawLine(False) # 6 t.left(90) IsDrawLine(True) if num in [0,3, 4, 5, 6, 7, 8, 9] else IsDrawLine(False) #第七划 t.right(90) t.penup() return def DrawNixieTube(ls): # 打印 冒号‘ :’ for i in ls: if i == ":": IsDrawColon() else: DrawNum(eval(i)) t.forward(20) #数字间间隔20个像素 return DrawInit() #画布初始化 DrawNixieTube("20:20") # 打印 20:20 t.done()

最新回复(0)