Skip to content

Exception thrown if text is not set on creation but updated later #45

Closed
@jimbobbennett

Description

@jimbobbennett

The recent changes in 2.6.0 have introduced an exception if the text is not set on a label when it is created, but is set later.

To reproduce:

import board
import terminalio
from adafruit_display_text import label


text = "Hello world"
text_area = label.Label(terminalio.FONT, max_glyphs=15)
text_area.x = 10
text_area.y = 10
text_area.text = text
board.DISPLAY.show(text_area)
while True:
    pass

This is a version of the SimpleTest example but instead of setting the text in the Label constructor, the text is set later.

Not setting the text parameter causes the _boundingbox property to be initialized to None.

When the text property is set later, the property setter retrieves the anchored_position value:

@text.setter
def text(self, new_text):
    current_anchored_position = self.anchored_position

This in turn uses the bounding box and assumes that it has a value rather than being None:

@property
def anchored_position(self):
    """Position relative to the anchor_point. Tuple containing x,y
       pixel coordinates."""
    return (
        int(
            self.x
            + self._boundingbox[0]
            + self._anchor_point[0] * self._boundingbox[2]
        ),
        int(
            self.y
            + self._boundingbox[1]
            + self._anchor_point[1] * self._boundingbox[3]
        ),
    )

This raises an exception:

Traceback (most recent call last):
  File "code.py", line 109, in <module>
  File "adafruit_display_text/label.py", line 241, in text
  File "adafruit_display_text/label.py", line 281, in anchored_position
TypeError: 'NoneType' object is not subscriptable

The workaround is to always set the text in the constructor. A quick fix could be to change the default value from None to "", that way the bounding box is always created.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions