刚刚学完七段数位管绘制的实例,突发奇想,想能不能用面对对象编程的思想绘制数码管,于是就有了这条博客
这段问题里的难点是对类方法的定义,具体有多少中方法需要自己在绘制过程中发现。
class Line:
def line1(self):
turtle.fd(100)
turtle.right(90)
def line2(self):
turtle.seth(90)
turtle.fd(100)
turtle.right(90)
def line3(self):
turtle.penup()
turtle.seth(0)
turtle.fd(14)
turtle.pendown()
def line4(self):
turtle.penup()
def line5(self):
turtle.pendown()
随机颜色的实现不算难,只是有一个注意的地方:python里的rgb颜色参数模式默认是0-1 用turtle的话需要用turtle.colormode(255) 语句把模式转换成0-255。
turtle.colormode(255)
def colorchoose():
a, b, c = random.randrange(0, 256), random.randrange(0, 256), random.randrange(0, 256)
color = (a, b, c)
return color
import turtle import time import random #随机颜色的模块# turtle.colormode(255) def colorchoose(): a, b, c = random.randrange(0, 256), random.randrange(0, 256), random.randrange(0, 256) color = (a, b, c) return color #准备 turtle.setup(1000,600) turtle.pensize(4) turtle.penup() turtle.goto(-475,0) turtle.seth(0) turtle.pendown() #定义一个包含图标可能的运动行为的方法的类 class Line: def line1(self): turtle.fd(100) turtle.right(90) def line2(self): turtle.seth(90) turtle.fd(100) turtle.right(90) def line3(self): turtle.penup() turtle.seth(0) turtle.fd(14) turtle.pendown() def line4(self): turtle.penup() def line5(self): turtle.pendown() a = Line()#实例化这个类 t1 = time.gmtime() #获取计算机可识别的当前的时间 time = time.strftime('%Y%m%d',t1) #将时间转化为人类可识别的时间 for i in range(8): turtle.pencolor(colorchoose()) (a.line5(),a.line1())if int(time[i]) in [2,3,4,5,6,8,9] else (a.line4(),a.line1()) (a.line5(),a.line1())if int(time[i]) in [0,1,3,4,5,6,7,8,9] else(a.line4(),a.line1()) (a.line5(),a.line1())if int(time[i]) in [0,2,3,5,6,8,9] else(a.line4(),a.line1()) (a.line5(),a.line1())if int(time[i]) in [0,2,6,8] else(a.line4(),a.line1()) (a.line5(),a.line2())if int(time[i]) in [0,4,5,6,8,9] else(a.line4(),a.line2()) (a.line5(),a.line1())if int(time[i]) in [0,2,3,5,6,7,8,9] else(a.line4(),a.line1()) (a.line5(),a.line1())if int(time[i]) in [0,1,2,3,4,6,7,8,9] else(a.line4(),a.line1()) a.line3() '''通过在循环中不断调用类中的方法达到绘制时间数位管的效果''' turtle.done()
说明是在2022年11月30日绘制的