六年多之后,这个问题值得回答。有点。代替实现 14 段字母数字显示,我将使用 7 个七段(十六进制)数字显示来演示基本思想。我将使用Wikipedia 中这篇七段显示文章中的约定。此外,我将定义一个自定义海龟光标,而不是绘制线段,并根据需要对其进行标记:
from turtle import Screen, Turtle
SCALE = 1.75 # arbitrarily scale digits larger or smaller
CURSOR_SIZE = 25 # maximum dimension of our custom turtle cursor
SPACING = CURSOR_SIZE * 1.25 * SCALE # space from start of one digit to the next
DIGITS = { # which segments to turn on encoded as bits
'0': 0x7E,
'1': 0x30,
'2': 0x6D,
'3': 0x79,
'4': 0x33,
'5': 0x5B,
'6': 0x5F,
'7': 0x70,
'8': 0x7F,
'9': 0x7B,
'A': 0x77,
'B': 0x1F,
'C': 0x4E,
'D': 0x3D,
'E': 0x4F,
'F': 0x47,
}
def display_number(turtle, number):
for digit in str(number):
bits = DIGITS[digit]
for bit in range(7):
if 2 ** bit & bits:
position = turtle.position()
segments[bit](turtle)
turtle.stamp()
turtle.setheading(0)
turtle.setposition(position)
turtle.forward(SPACING)
def segment_A(turtle): # top
turtle.setheading(90)
turtle.sety(turtle.ycor() + 20 * SCALE)
def segment_B(turtle): # right upper
turtle.setposition(turtle.xcor() + 10 * SCALE, turtle.ycor() + 10 * SCALE)
def segment_C(turtle): # right lower
turtle.setposition(turtle.xcor() + 10 * SCALE, turtle.ycor() - 10 * SCALE)
def segment_D(turtle): # bottom
turtle.setheading(90)
turtle.sety(turtle.ycor() - 20 * SCALE)
def segment_E(turtle): # left lower
turtle.setposition(turtle.xcor() - 10 * SCALE, turtle.ycor() - 10 * SCALE)
def segment_F(turtle): # left upper
turtle.setposition(turtle.xcor() - 10 * SCALE, turtle.ycor() + 10 * SCALE)
def segment_G(turtle): # center
turtle.setheading(90)
segments = [segment_G, segment_F, segment_E, segment_D, segment_C, segment_B, segment_A]
screen = Screen()
screen.setup(950, 200)
screen.register_shape('segment', ((-12.5, 0), (-10, 2.5), (10, 2.5), (12.5, 0), (10, -2.5), (-10, -2.5))) # <=>
turtle = Turtle('segment', visible=False)
turtle.shapesize(SCALE)
turtle.speed('fastest')
turtle.penup()
turtle.setx(SPACING - screen.window_width() / 2)
display_number(turtle, "0123456789ABCDEF")
screen.exitonclick()
将段数增加到 14,使文本多行打印和添加小数点都留给读者作为练习。