p ython七段数码管时分秒
时间: 2023-07-11 10:11:03 浏览: 88
好的,我可以帮你解决这个问题。下面是 Python 代码实现七段数码管显示时分秒:
```python
import time
# 定义数字 0~9 的七段数码管编码
digit = {
0: ['1111110', '0110000', '1101101', '1111001', '0110011', '1011011', '1011111', '1110000', '1111111', '1111011'],
1: ['0110000', '0010000', '0100000', '0010000', '0010000', '0010000', '0110000', '0010000', '0110000', '0010000'],
2: ['1111110', '0010000', '1101101', '1111111', '1110000', '1011111', '1111101', '0000001', '1111111', '1111011'],
3: ['1111110', '0010000', '1101101', '1111111', '0010000', '1101101', '1111111', '0010000', '1111111', '1111011'],
4: ['0110011', '0110011', '0110011', '1111111', '0010010', '0010010', '1111111', '0010010', '1111111', '1111011'],
5: ['1111110', '1000000', '1011111', '1111111', '0010000', '1101101', '1111111', '0010000', '1111111', '1111011'],
6: ['1111110', '0110000', '1011111', '1111111', '0110011', '1101101', '1111111', '1110000', '1111111', '1111011'],
7: ['1111110', '0010000', '1101101', '0010010', '0010010', '0010010', '0010010', '0010010', '0010010', '0010010'],
8: ['1111110', '0110000', '1101101', '1111111', '0110011', '1101101', '1111111', '0110011', '1111111', '1111011'],
9: ['1111110', '0110000', '1101101', '1111111', '0010011', '1111111', '1111111', '0010010', '1111111', '1111011']
}
# 获取当前时间的时分秒
def get_time():
t = time.localtime()
h = str(t.tm_hour).zfill(2)
m = str(t.tm_min).zfill(2)
s = str(t.tm_sec).zfill(2)
return h, m, s
# 显示数字的七段数码管
def show_digit(d, n):
code = digit[d][n]
for i in range(7):
if code[i] == '1':
print('\033[1;31;40m#\033[0m', end='')
else:
print(' ', end='')
if i == 2 or i == 4:
print(' ', end='')
print()
# 显示时间的七段数码管
def show_time(h, m, s):
print()
for i in range(7):
for j in range(2):
if i == 0:
if j == 0:
show_digit(int(h[0]), i)
else:
show_digit(int(h[1]), i)
elif i == 3:
if j == 0:
show_digit(int(m[0]), i)
else:
show_digit(int(m[1]), i)
elif i == 6:
if j == 0:
show_digit(int(s[0]), i)
else:
show_digit(int(s[1]), i)
else:
print(' ' * 16, end='')
print()
# 主程序入口
if __name__ == '__main__':
while True:
h, m, s = get_time()
show_time(h, m, s)
time.sleep(1)
print('\033[7A', end='')
```
运行这段代码会在终端显示当前时间的七段数码管,每秒钟更新一次。注意,这段代码只能在支持 ANSI 转义序列的终端上运行,比如 macOS 和 Linux 的终端。
阅读全文