ITPub博客

首页 > 应用开发 > IT综合 > Python实现七段数码管字母绘制的原理与实践

Python实现七段数码管字母绘制的原理与实践

投稿 IT综合 作者:bhluo 时间:2025-12-18 17:08:58 0 删除 编辑

# Python实现七段数码管字母绘制的原理与实践


## 引言:七段数码管的历史与现代应用


七段数码管作为数字显示的基础元件,自上世纪60年代发明以来,在计算器、电子钟表、仪器仪表等领域广泛应用。尽管现代显示技术日新月异,七段数码管因其结构简单、成本低廉、显示清晰等特点,仍然在许多场景中发挥着重要作用。本文将通过Python编程,深入探讨七段数码管的工作原理,并实现字母显示功能,将数字显示扩展至字符显示。


## 七段数码管基础原理


### 结构与段位编码


七段数码管由七个发光二极管(LED)段组成,通常标记为a到g。每个段可以独立控制,通过不同段的组合显示数字0-9。


```python

# 七段数码管段位布局图示

"""

     a

    ---

 f |   | b

    -g-

 e |   | c

    ---

     d

"""


# 数字0-9的段位编码

SEGMENT_ENCODINGS = {

    '0': {'a', 'b', 'c', 'd', 'e', 'f'},          # abcdef

    '1': {'b', 'c'},                              # bc

    '2': {'a', 'b', 'g', 'e', 'd'},               # abged

    '3': {'a', 'b', 'g', 'c', 'd'},               # abgcd

    '4': {'f', 'g', 'b', 'c'},                    # fgbc

    '5': {'a', 'f', 'g', 'c', 'd'},               # afgcd

    '6': {'a', 'f', 'e', 'd', 'c', 'g'},          # afedcg

    '7': {'a', 'b', 'c'},                         # abc

    '8': {'a', 'b', 'c', 'd', 'e', 'f', 'g'},     # abcdefg

    '9': {'a', 'b', 'c', 'd', 'f', 'g'},          # abcdfg

}


# 十六进制字符的段位编码(A-F)

HEX_ENCODINGS = {

    'A': {'a', 'b', 'c', 'e', 'f', 'g'},          # abcefg

    'b': {'c', 'd', 'e', 'f', 'g'},               # cdefg

    'C': {'a', 'd', 'e', 'f'},                    # adef

    'd': {'b', 'c', 'd', 'e', 'g'},               # bcdeg

    'E': {'a', 'd', 'e', 'f', 'g'},               # adefg

    'F': {'a', 'e', 'f', 'g'},                    # aefg

}

```


### 字母显示的挑战与解决方案


传统七段数码管主要用于显示数字,但通过巧妙的段位组合,也可以显示部分字母。这需要考虑字母的可识别性和段位的物理限制。


```python

class SevenSegmentLogic:

    """七段数码管逻辑控制器"""

    

    @staticmethod

    def get_character_segments(char: str) -> set:

        """

        获取字符对应的段位集合

        

        Args:

            char: 要显示的字符(0-9, A-F, 部分字母)

        

        Returns:

            需要点亮的段位集合

        """

        char = char.upper()

        

        # 数字编码

        if char in SEGMENT_ENCODINGS:

            return SEGMENT_ENCODINGS[char]

        

        # 十六进制字符编码

        if char in HEX_ENCODINGS:

            return HEX_ENCODINGS[char]

        

        # 扩展字母编码(小写转换为大写处理)

        extended_encodings = {

            'H': {'b', 'c', 'e', 'f', 'g'},       # bcefg

            'I': {'b', 'c'},                      # bc (与1相同)

            'J': {'b', 'c', 'd'},                 # bcd

            'L': {'d', 'e', 'f'},                 # def

            'O': {'a', 'b', 'c', 'd', 'e', 'f'},  # abcdef (与0相同)

            'P': {'a', 'b', 'e', 'f', 'g'},       # abefg

            'S': {'a', 'f', 'g', 'c', 'd'},       # afgcd (与5相同)

            'U': {'b', 'c', 'd', 'e', 'f'},       # bcdef

            'Y': {'b', 'c', 'd', 'f', 'g'},       # bcdfg

            'Z': {'a', 'b', 'g', 'e', 'd'},       # abged (与2相同)

        }

        

        if char in extended_encodings:

            return extended_encodings[char]

        

        # 默认返回空集合(不显示)

        return set()

    

    @staticmethod

    def validate_character(char: str) -> bool:

        """

        验证字符是否可以被七段数码管显示

        

        Args:

            char: 要验证的字符

        

        Returns:

            是否可显示

        """

        char = char.upper()

        

        # 检查是否在可显示字符集中

        displayable_chars = set('0123456789ABCDEFHIJLOPSUYZ')

        return char in displayable_chars

    

    @staticmethod

    def get_segment_matrix(segments: set) -> list:

        """

        将段位集合转换为7x5的矩阵表示

        

        Returns:

            7x5的矩阵,1表示点亮,0表示熄灭

        """

        # 定义每个段在7x5矩阵中的位置

        segment_positions = {

            'a': [(0, 1), (0, 2), (0, 3)],

            'b': [(1, 4), (2, 4)],

            'c': [(4, 4), (5, 4)],

            'd': [(6, 1), (6, 2), (6, 3)],

            'e': [(4, 0), (5, 0)],

            'f': [(1, 0), (2, 0)],

            'g': [(3, 1), (3, 2), (3, 3)],

        }

        

        # 创建7x5的矩阵

        matrix = [[0 for _ in range(5)] for _ in range(7)]

        

        # 根据段位设置矩阵值

        for segment in segments:

            if segment in segment_positions:

                for row, col in segment_positions[segment]:

                    matrix[row][col] = 1

        

        return matrix

    

    @staticmethod

    def segment_to_binary(segments: set) -> int:

        """

        将段位集合转换为二进制表示

        

        Returns:

            8位二进制数(最高位为小数点)

        """

        segment_order = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'dp']  # dp为小数点

        binary_value = 0

        

        for i, segment in enumerate(segment_order):

            if segment in segments:

                binary_value |= (1 << i)

        

        return binary_value

```


## 使用Turtle图形库绘制


### 基础绘制函数


```python

import turtle

import time

from typing import List, Tuple


class SevenSegmentDisplay:

    """七段数码管显示器"""

    

    def __init__(self, size: int = 40, 

                 on_color: str = "#00FF00",

                 off_color: str = "#003300",

                 bg_color: str = "black"):

        """

        初始化七段数码管显示器

        

        Args:

            size: 段位长度

            on_color: 点亮颜色

            off_color: 熄灭颜色

            bg_color: 背景颜色

        """

        self.size = size

        self.>

        self.off_color = off_color

        self.bg_color = bg_color

        

        # 设置turtle

        self.screen = turtle.Screen()

        self.screen.bgcolor(bg_color)

        self.screen.title("七段数码管字母显示")

        

        self.pen = turtle.Turtle()

        self.pen.speed(0)

        self.pen.hideturtle()

        self.pen.pensize(3)

        

        # 段位坐标定义(相对于中心点)

        self.segment_coords = {

            'a': [(-size, size*2), (size, size*2)],

            'b': [(size, size*2), (size, 0)],

            'c': [(size, -size), (size, -size*2)],

            'd': [(-size, -size*2), (size, -size*2)],

            'e': [(-size, -size*2), (-size, -size)],

            'f': [(-size, size*2), (-size, 0)],

            'g': [(-size, 0), (size, 0)],

        }

    

    def draw_segment(self, segment: str, is_on: bool = True):

        """

        绘制单个段位

        

        Args:

            segment: 段位标识符(a-g)

            is_on: 是否点亮

        """

        if segment not in self.segment_coords:

            return

        

        color = self.on_color if is_on else self.off_color

        self.pen.pencolor(color)

        

        start, end = self.segment_coords[segment]

        

        self.pen.penup()

        self.pen.goto(start)

        self.pen.pendown()

        self.pen.goto(end)

        self.pen.penup()

    

    def draw_character(self, char: str, 

                      x: float = 0, 

                      y: float = 0):

        """

        在指定位置绘制字符

        

        Args:

            char: 要显示的字符

            x: X坐标

            y: Y坐标

        """

        # 移动到指定位置

        self.pen.penup()

        self.pen.goto(x, y)

        

        # 获取段位信息

        segments = SevenSegmentLogic.get_character_segments(char)

        

        # 绘制所有段位

        for segment in ['a', 'b', 'c', 'd', 'e', 'f', 'g']:

            is_on = segment in segments

            self.draw_segment(segment, is_on)

    

    def draw_digit(self, digit: int, 

                  x: float = 0, 

                  y: float = 0):

        """

        绘制数字

        

        Args:

            digit: 数字0-9

            x: X坐标

            y: Y坐标

        """

        if 0 <= digit <= 9:

            self.draw_character(str(digit), x, y)

    

    def draw_text(self, text: str, 

                 spacing: float = 120,

                 start_x: float = -300):

        """

        绘制文本字符串

        

        Args:

            text: 要显示的文本

            spacing: 字符间距

            start_x: 起始X坐标

        """

        x = start_x

        y = 0

        

        for i, char in enumerate(text.upper()):

            if SevenSegmentLogic.validate_character(char):

                self.draw_character(char, x, y)

                x += spacing

            

            # 换行处理

            if i > 0 and i % 8 == 0:  # 每行8个字符

                x = start_x

                y -= spacing * 1.5

    

    def draw_with_animation(self, text: str,

                          delay: float = 0.5,

                          spacing: float = 120):

        """

        以动画方式绘制文本

        

        Args:

            text: 要显示的文本

            delay: 字符显示延迟

            spacing: 字符间距

        """

        x = -300

        y = 0

        

        for i, char in enumerate(text.upper()):

            if SevenSegmentLogic.validate_character(char):

                # 逐个段位绘制,创建动画效果

                segments = SevenSegmentLogic.get_character_segments(char)

                

                for segment in ['a', 'b', 'c', 'd', 'e', 'f', 'g']:

                    is_on = segment in segments

                    self.draw_segment(segment, is_on)

                    time.sleep(delay / 7)  # 每个段位有延迟

                

                x += spacing

            

            # 换行处理

            if i > 0 and i % 8 == 0:

                x = -300

                y -= spacing * 1.5

            

            time.sleep(delay)

    

    def clear_display(self):

        """清除显示"""

        self.pen.clear()

        self.screen.bgcolor(self.bg_color)


    

    def demo(self):

        """演示功能"""

        self.clear_display()

        

        # 显示数字0-9

        print("显示数字 0-9:")

        for i in range(10):

            self.draw_digit(i, x=-200 + i*60, y=100)

        

        time.sleep(2)

        self.clear_display()

        

        # 显示十六进制字符

        print("显示十六进制字符 A-F:")

        hex_chars = 'ABCDEF'

        for i, char in enumerate(hex_chars):

            self.draw_character(char, x=-150 + i*60, y=100)

        

        time.sleep(2)

        self.clear_display()

        

        # 显示单词

        print("显示单词 'HELLO':")

        self.draw_text("HELLO", spacing=100, start_x=-200)

        

        time.sleep(2)

        self.clear_display()

        

        # 显示句子

        print("显示句子 'PYTHON 3.9':")

        self.draw_text("PYTHON 3.9", spacing=80, start_x=-300)

        

        # 保持窗口打开

        self.screen.mainloop()

```


## 使用Pygame实现交互式显示


### 创建更现代的显示界面


```python

import pygame

import sys

from typing import Dict, List, Tuple


class PygameSevenSegment:

    """基于Pygame的七段数码管显示器"""

    

    def __init__(self, 

                 segment_width: int = 10,

                 segment_length: int = 40,

                 spacing: int = 10,

                 on_color: Tuple[int, int, int] = (0, 255, 0),

                 off_color: Tuple[int, int, int] = (30, 30, 30),

                 bg_color: Tuple[int, int, int] = (0, 0, 0)):

        """

        初始化Pygame显示器

        

        Args:

            segment_width: 段位宽度

            segment_length: 段位长度

            spacing: 段位间距

            on_color: 点亮颜色 (R, G, B)

            off_color: 熄灭颜色 (R, G, B)

            bg_color: 背景颜色 (R, G, B)

        """

        self.segment_width = segment_width

        self.segment_length = segment_length

        self.spacing = spacing

        self.>

        self.off_color = off_color

        self.bg_color = bg_color

        

        # 计算显示区域大小

        self.display_width = segment_length * 2 + segment_width * 3

        self.display_height = segment_length * 2 + segment_width * 3

        

        # 初始化pygame

        pygame.init()

        self.screen = pygame.display.set_mode((800, 600))

        pygame.display.set_caption("七段数码管字母显示器")

        

        # 创建字体

        self.font = pygame.font.SysFont('consolas', 24)

        

        # 段位多边形定义

        self.segment_polygons = self._create_segment_polygons()

    

    def _create_segment_polygons(self) -> Dict[str, List[Tuple[int, int]]]:

        """

        创建每个段位的多边形顶点

        

        Returns:

            段位标识符到多边形顶点的映射

        """

        w = self.segment_width

        l = self.segment_length

        

        # 水平段位(a, g, d)

        horizontal_polygon = [

            (0, 0), (l, 0), 

            (l - w//2, w), (w//2, w)

        ]

        

        # 垂直段位(b, c, e, f)

        vertical_polygon = [

            (0, 0), (w, 0),

            (w, l), (0, l)

        ]

        

        return {

            'a': self._rotate_polygon(horizontal_polygon, 0),

            'b': self._rotate_polygon(vertical_polygon, 0),

            'c': self._rotate_polygon(vertical_polygon, 180),

            'd': self._rotate_polygon(horizontal_polygon, 180),

            'e': self._rotate_polygon(vertical_polygon, 270),

            'f': self._rotate_polygon(vertical_polygon, 90),

            'g': self._rotate_polygon(horizontal_polygon, 0),

        }

    

    def _rotate_polygon(self, polygon: List[Tuple[int, int]], 

                       angle: int) -> List[Tuple[int, int]]:

        """

        旋转多边形

        

        Args:

            polygon: 多边形顶点列表

            angle: 旋转角度(度)

        

        Returns:

            旋转后的多边形

        """

        import math

        

        # 转换角度为弧度

        theta = math.radians(angle)

        

        # 计算旋转中心(假设为原点)

        rotated = []

        for x, y in polygon:

            # 旋转变换

            x_rot = x * math.cos(theta) - y * math.sin(theta)

            y_rot = x * math.sin(theta) + y * math.cos(theta)

            rotated.append((x_rot, y_rot))

        

        return rotated

    

    def _get_segment_position(self, segment: str) -> Tuple[int, int]:

        """

        获取段位的显示位置

        

        Args:

            segment: 段位标识符


        www.kf.zizhitong.cn>www.pt.zizhitong.cn

        Returns:

            (x, y) 坐标

        """

        l = self.segment_length

        w = self.segment_width

        s = self.spacing

        

        positions = {

            'a': (w + s, 0),

            'b': (l + w + s*2, w + s),

            'c': (l + w + s*2, l + w*2 + s*3),

            'd': (w + s, l*2 + w*2 + s*4),

            'e': (0, l + w*2 + s*3),

            'f': (0, w + s),

            'g': (w + s, l + w + s*2),

        }

        

        return positions.get(segment, (0, 0))

    

    def draw_segment(self, surface: pygame.Surface, 

                    segment: str, 

                    is_on: bool = True,

                    offset_x: int = 0,

                    offset_y: int = 0):

        """

        在表面上绘制段位

        

        Args:

            surface: Pygame表面

            segment: 段位标识符

            is_on: 是否点亮

            offset_x: X偏移

            offset_y: Y偏移

        """

        if segment not in self.segment_polygons:

            return

        

        color = self.on_color if is_on else self.off_color

        

        # 获取多边形和位置

        polygon = self.segment_polygons[segment]

        pos_x, pos_y = self._get_segment_position(segment)

        

        # 应用偏移

        pos_x += offset_x

        pos_y += offset_y

        

        # 创建实际的多边形顶点

        actual_polygon = [(x + pos_x, y + pos_y) for (x, y) in polygon]

        

        # 绘制多边形

        pygame.draw.polygon(surface, color, actual_polygon)

        

        # 添加边框效果

        border_color = (min(255, color[0] + 50), 

                       min(255, color[1] + 50), 

                       min(255, color[2] + 50)) if is_on else self.off_color

        pygame.draw.polygon(surface, border_color, actual_polygon, 2)

    

    def draw_character(self, surface: pygame.Surface,

                      char: str,

                      x: int = 0,

                      y: int = 0):

        """

        绘制字符

        

        Args:

            surface: Pygame表面

            char: 要显示的字符

            x: X坐标

            y: Y坐标

        """

        segments = SevenSegmentLogic.get_character_segments(char)

        

        # 绘制所有段位

        for segment in ['a', 'b', 'c', 'd', 'e', 'f', 'g']:

            is_on = segment in segments

            self.draw_segment(surface, segment, is_on, x, y)

        

        # 显示字符标签

        if char:

            label = self.font.render(char, True, (255, 255, 255))

            label_rect = label.get_rect(center=(x + self.display_width//2, 

                                               y + self.display_height + 20))

            surface.blit(label, label_rect)

    

    def draw_text(self, surface: pygame.Surface,

                 text: str,

                 x: int = 50,

                 y: int = 50,

                 spacing: int = 100):

        """

        绘制文本

        

        Args:

            surface: Pygame表面

            text: 要显示的文本

            x: 起始X坐标

            y: 起始Y坐标

            spacing: 字符间距

        """

        current_x = x

        current_y = y

        

        for i, char in enumerate(text.upper()):

            if SevenSegmentLogic.validate_character(char):

                self.draw_character(surface, char, current_x, current_y)

                current_x += spacing + self.display_width

                

                # 换行处理

                if current_x + self.display_width > 750:

                    current_x = x

                    current_y += self.display_height + 80

    

    def create_digital_clock(self, hour: int, minute: int, 

                           second: int) -> pygame.Surface:

        """

        创建数字时钟显示

        

        Args:

            hour: 小时

            minute: 分钟

            second: 秒

        

        Returns:

            时钟表面

        """

        clock_surface = pygame.Surface((self.display_width * 8 + 200, 

                                       self.display_height + 50))

        clock_surface.fill(self.bg_color)

        

        # 格式化时间字符串

        time_str = f"{hour:02d}{minute:02d}{second:02d}"

        

        # 绘制时间

        x_pos = 20

        for i, char in enumerate(time_str):

            self.draw_character(clock_surface, char, x_pos, 25)

            x_pos += self.display_width + 10

            

            # 添加冒号分隔符

            if i == 1 or i == 3:

                # 绘制冒号

                colon_radius = 5

                colon_y1 = 25 + self.display_height//3

                colon_y2 = 25 + self.display_height*2//3

                

                pygame.draw.circle(clock_surface, self.on_color,

                                 (x_pos + 5, colon_y1), colon_radius)

                pygame.draw.circle(clock_surface, self.on_color,

                                 (x_pos + 5, colon_y2), colon_radius)

                x_pos += 20

        

        return clock_surface

    

    def run_demo(self):

        """运行演示程序"""

        clock = pygame.time.Clock()

        running = True

        

        # 演示文本

        demo_texts = [

            "0123456789",

            "ABCDEF",

            "HELLO",

            "PYTHON",

            "SEGMENT",

            "DISPLAY",

        ]

        

        current_text_index = 0

        text_change_timer = 0

        text_change_interval = 3000  # 3秒

        

        # 时钟显示变量

        show_clock = False

        last_time_update = 0

        

        while running:

            current_time = pygame.time.get_ticks()

            

            # 处理事件

            for event in pygame.event.get():

                if event.type == pygame.QUIT:

                    running = False

                elif event.type == pygame.KEYDOWN:

                    if event.key == pygame.K_SPACE:

                        show_clock = not show_clock

                    elif event.key == pygame.K_RIGHT:

                        current_text_index = (current_text_index + 1) % len(demo_texts)

                    elif event.key == pygame.K_LEFT:

                        current_text_index = (current_text_index - 1) % len(demo_texts)

            

            # 清屏

            self.screen.fill(self.bg_color)

            

            if show_clock:

                # 显示时钟

                current_datetime = pygame.time.get_ticks()

                if current_datetime - last_time_update > 1000:  # 每秒更新

                    last_time_update = current_datetime

                

                # 获取当前时间(模拟)

                hours = (current_datetime // 3600000) % 24

                minutes = (current_datetime // 60000) % 60

                seconds = (current_datetime // 1000) % 60

                

                clock_surface = self.create_digital_clock(hours, minutes, seconds)

                self.screen.blit(clock_surface, (50, 200))

                

                # 显示提示

                prompt = self.font.render("按空格键切换显示模式", True, (255, 255, 255))

                self.screen.blit(prompt, (250, 500))

                

            else:

                # 轮换显示文本

                if current_time - text_change_timer > text_change_interval:

                    current_text_index = (current_text_index + 1) % len(demo_texts)

                    text_change_timer = current_time

                

                current_text = demo_texts[current_text_index]

www.vs.zizhitong.cn>www.rb.zizhitong.cn

                

                # 绘制文本

                self.draw_text(self.screen, current_text, 50, 150, 80)

                

                # 显示控制提示

                controls = [

                    "控制说明:",

                    "左右方向键: 切换显示文本",

                    "空格键: 切换时钟/文本模式",

                    "ESC键: 退出程序"

                ]

                

                for i, line in enumerate(controls):

                    text_surface = self.font.render(line, True, (200, 200, 200))

                    self.screen.blit(text_surface, (50, 450 + i * 30))

            

            # 显示标题

            title = pygame.font.SysFont('consolas', 36).render(

                "七段数码管字母显示器", True, (255, 255, 0))

            self.screen.blit(title, (200, 30))

            

            # 显示当前模式

            mode_text = "时钟模式" if show_clock else f"文本模式: {demo_texts[current_text_index]}"

            mode_surface = self.font.render(mode_text, True, (0, 255, 255))

            self.screen.blit(mode_surface, (300, 100))

            

            pygame.display.flip()

            clock.tick(60)

        

        pygame.quit()

        sys.exit()

```


## 高级功能:自定义字母与动画效果


### 创建自定义字母编码


```python

import json

from pathlib import Path


class CustomSegmentEncoder:

    """自定义七段数码管编码器"""

    

    def __init__(self, encoding_file: str = None):

        """

        初始化编码器

        

        Args:

            encoding_file: 编码定义文件路径

        """

        self.custom_encodings = {}

        

        if encoding_file and Path(encoding_file).exists():

            self.load_encodings(encoding_file)

        else:

            self.load_default_encodings()

    

    def load_default_encodings(self):

        """加载默认编码"""

        # 扩展更多字母的显示方式

        self.custom_encodings = {

            # 小写字母(部分可以显示)

            'a': {'a', 'b', 'c', 'e', 'f', 'g'},

            'c': {'a', 'd', 'e', 'f'},

            'e': {'a', 'd', 'e', 'f', 'g'},

            'f': {'a', 'e', 'f', 'g'},

            'h': {'c', 'e', 'f', 'g'},

            'i': {'e', 'f'},

            'l': {'d', 'e', 'f'},

            'o': {'a', 'b', 'c', 'd', 'e', 'f'},

            'p': {'a', 'b', 'e', 'f', 'g'},

            's': {'a', 'f', 'g', 'c', 'd'},

            'u': {'b', 'c', 'd', 'e', 'f'},

            

            # 符号

            '-': {'g'},

            '_': {'d'},

            '=': {'d', 'g'},

            '[': {'a', 'd', 'e', 'f'},

            ']': {'a', 'b', 'c', 'd'},

            '(': {'a', 'd', 'e', 'f'},

            ')': {'a', 'b', 'c', 'd'},

            

            # 箭头符号

            '↑': {'a', 'b', 'f'},

            '↓': {'c', 'd', 'e'},

            '→': {'b', 'c', 'g'},

            '←': {'e', 'f', 'g'},

        }

    

    def save_encodings(self, filepath: str):

        """

        保存编码到文件

        

        Args:

            filepath: 文件路径

        """

        # 将集合转换为列表以便JSON序列化

        serializable = {char: list(segments) 

                       for char, segments in self.custom_encodings.items()}

        

        with open(filepath, 'w', encoding='utf-8') as f:

            json.dump(serializable, f, ensure_ascii=False, indent=2)

    

    def load_encodings(self, filepath: str):

        """

        从文件加载编码

        

        Args:

            filepath: 文件路径

        """

        try:

            with open(filepath, 'r', encoding='utf-8') as f:

                loaded = json.load(f)

            

            # 将列表转换回集合

            self.custom_encodings = {char: set(segments) 

                                    for char, segments in loaded.items()}

        

        except Exception as e:

            print(f"加载编码文件失败: {e}")

            self.load_default_encodings()

    

    def create_custom_character(self, char: str, 

                               segments: List[str]) -> bool:

www.mo.zizhitong.cn>www.af.zizhitong.cn>

        """

        创建自定义字符编码

        

        Args:

            char: 字符

            segments: 需要点亮的段位列表

        

        Returns:

            是否创建成功

        """

        if not segments:

            return False

        

        # 验证段位有效性

        valid_segments = {'a', 'b', 'c', 'd', 'e', 'f', 'g'}

        if not all(s in valid_segments for s in segments):

            print(f"无效段位: 只能使用 {valid_segments}")

            return False

        

        self.custom_encodings[char] = set(segments)

        return True

    

    def get_encoding(self, char: str) -> set:

        """

        获取字符编码

        

        Args:

            char: 字符

        

        Returns:

            段位集合

        """

        return self.custom_encodings.get(char, set())

    

    def preview_character(self, char: str, 

                         display: SevenSegmentDisplay):

        """

        预览字符显示效果

        

        Args:

            char: 字符

            display: 显示器实例

        """

        segments = self.get_encoding(char)

        

        print(f"字符 '{char}' 的段位编码: {sorted(segments)}")

        

        # 显示字符

        display.clear_display()

        display.draw_character(char)

        

        # 显示段位图

        matrix = SevenSegmentLogic.get_segment_matrix(segments)

        print("矩阵表示:")

        for row in matrix:

            print(' '.join('■' if cell else '□' for cell in row))


class AnimatedSegmentDisplay:

    """带动画的七段数码管显示器"""

www.bs.zizhitong.cn>www.ly.zizhitong.cn

    

    def __init__(self, base_display: SevenSegmentDisplay):

        """

        初始化动画显示器

        

        Args:

            base_display: 基础显示器实例

        """

        self.display = base_display

    

    def scrolling_text(self, text: str, 

                      speed: float = 0.2,

                      spacing: float = 120):

        """

        滚动文本动画

        

        Args:

            text: 要显示的文本

            speed: 滚动速度(秒/字符)

            spacing: 字符间距

        """

        import time

        

        text = text.upper()

        text_width = len(text) * spacing

        

        # 初始位置:文本完全在右侧

        x_offset = 800

        

        while x_offset > -text_width:

            self.display.clear_display()

            

            # 绘制可见部分的文本

            current_x = x_offset

            for char in text:

                if current_x > -spacing and current_x < 800:

                    self.display.draw_character(char, current_x, 0)

                current_x += spacing

            

            # 更新位置

            x_offset -= spacing / 4

            

            time.sleep(speed)

    

    def count_animation(self, start: int, end: int,

                       delay: float = 0.5):

        """

        计数动画

        

        Args:

            start: 起始数字

            end: 结束数字

            delay: 延迟时间

        """

        import time

        

        for number in range(start, end + 1):

            self.display.clear_display()

            

            # 绘制数字

            digits = str(number)

            x_pos = -len(digits) * 30 + 30

            

            for digit in digits:

                self.display.draw_digit(int(digit), x_pos, 0)

                x_pos += 60

            

            time.sleep(delay)

    

    def segment_test_pattern(self):

        """段位测试图案"""

        import time

        

        patterns = [

            {'a'}, {'b'}, {'c'}, {'d'}, {'e'}, {'f'}, {'g'},

            {'a', 'd'}, {'b', 'e'}, {'c', 'f'},

            {'a', 'g'}, {'b', 'g'}, {'c', 'g'}, {'d', 'g'}, {'e', 'g'}, {'f', 'g'},

            {'a', 'b', 'c', 'd', 'e', 'f', 'g'},  # 全亮

        ]

        

        for pattern in patterns:

            self.display.clear_display()

            

            # 显示当前段位

            for segment in pattern:

                self.display.draw_segment(segment, True)

            

            # 显示模式名称

            pattern_name = ''.join(sorted(pattern)) if pattern else "无"

            print(f"显示段位: {pattern_name}")

            

            time.sleep(0.5)

    

    def transition_effect(self, from_char: str, 

                         to_char: str,

                         steps: int = 10,

                         delay: float = 0.05):

        """

        字符过渡动画

        

        Args:

            from_char: 起始字符

            to_char: 目标字符

            steps: 过渡步数

            delay: 每步延迟

        """

        import time

        

        from_segments = SevenSegmentLogic.get_character_segments(from_char)

        to_segments = SevenSegmentLogic.get_character_segments(to_char)

        

        all_segments = {'a', 'b', 'c', 'd', 'e', 'f', 'g'}

        

        for step in range(steps + 1):

            self.display.clear_display()

            

            # 计算当前步骤的段位状态

            current_segments = set()

            progress = step / steps

            

            for segment in all_segments:

                from_on = segment in from_segments

                to_on = segment in to_segments

                

                # 决定是否点亮

                if from_on and to_on:

                    current_segments.add(segment)

                elif from_on and not to_on:

                    # 逐渐熄灭

                    if progress < 0.5:

                        current_se


来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/19545/viewspace-3105625/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2015-11-01

  • 博文量
    895
  • 访问量
    933968