用python的turtle画数码管
时间: 2023-12-25 08:22:31 浏览: 68
好的,以下是用Python的turtle库画数码管的代码:
```python
import turtle
# 画数码管
def draw_digit(digit, size):
# 画横线
if digit in [2, 3, 4, 5, 6, 8, 9]:
turtle.penup()
turtle.goto(0, 0)
turtle.pendown()
turtle.forward(size)
# 画上半横线
if digit in [0, 2, 3, 5, 6, 7, 8, 9]:
turtle.penup()
turtle.goto(0, size)
turtle.pendown()
turtle.right(90)
turtle.forward(size)
# 画下半横线
if digit in [0, 2, 3, 5, 6, 8, 9]:
turtle.penup()
turtle.goto(0, 0)
turtle.pendown()
turtle.right(90)
turtle.forward(size)
# 画左上竖线
if digit in [0, 4, 5, 6, 8, 9]:
turtle.penup()
turtle.goto(0, size)
turtle.pendown()
turtle.left(90)
turtle.forward(size)
# 画右上竖线
if digit in [0, 1, 2, 3, 4, 7, 8, 9]:
turtle.penup()
turtle.goto(size, size)
turtle.pendown()
turtle.right(90)
turtle.forward(size)
# 画左下竖线
if digit in [0, 2, 6, 8]:
turtle.penup()
turtle.goto(0, 0)
turtle.pendown()
turtle.left(90)
turtle.forward(size)
# 画右下竖线
if digit in [0, 1, 3, 4, 5, 6, 7, 8, 9]:
turtle.penup()
turtle.goto(size, 0)
turtle.pendown()
turtle.right(90)
turtle.forward(size)
# 测试
turtle.speed(0) # 设置画笔速度
turtle.pensize(5) # 设置画笔粗细
turtle.penup()
turtle.goto(-250, 0) # 设置起始位置
turtle.pendown()
draw_digit(0, 50) # 画数字 0
turtle.penup()
turtle.goto(-170, 0)
turtle.pendown()
draw_digit(1, 50) # 画数字 1
turtle.penup()
turtle.goto(-90, 0)
turtle.pendown()
draw_digit(2, 50) # 画数字 2
turtle.penup()
turtle.goto(10, 0)
turtle.pendown()
draw_digit(3, 50) # 画数字 3
turtle.penup()
turtle.goto(90, 0)
turtle.pendown()
draw_digit(4, 50) # 画数字 4
turtle.penup()
turtle.goto(170, 0)
turtle.pendown()
draw_digit(5, 50) # 画数字 5
turtle.penup()
turtle.goto(250, 0)
turtle.pendown()
draw_digit(6, 50) # 画数字 6
turtle.done() # 完成绘画
```
运行代码后,会得到一个绘制了数字 0-6 的数码管。你可以根据需要修改代码中的数字和大小参数来绘制不同的数码管。
阅读全文