Search code examples
pythonpyglet

pyglet - Retrieve width of Label


I have a label element for displaying text on the screen:

nameLabel = pyglet.text.Label(name, font_name='Tahoma', x=50, y=50, font_size=12, batch=batch.overlay2, height=self.scale_y, bold=True)

With the label I also have a pyglet.sprite.Sprite:

sprite = pyglet.sprite.Sprite.__init__(res.IMG_COLOR_BLACK, batch=batch.overlay1)

The image of this sprite is 1x1 pixels and I am using the scale_x and scale_y values to draw a rectangle.

I would like to set the width of this sprite to the width of the text, so that the text fits inside it.

I have tried using Label.width:

sprite.scale_x = nameLabel.width

However, the width is only returning None and therefore raising an error.

I can't think of any other way to retrieve the width of this label. Does anyone know how I can do this?

Thanks,

David.


Solution

  • I think you should use the content width and content height attributes. It should return the width and the height of the label rectangle.

    import pyglet
    
    window = pyglet.window.Window(1280, 720, "Labels", resizable=False)
    
    text = pyglet.text.Label("hello earthlings from space", x=640, y=360)
    text.italic = True
    text.bold = True
    text.color = (255, 200, 150, 255)
    text.font_size = 20
    print(text.content_width)
    print(text.content_height)
    
    @window.event
    def on_draw():
        window.clear()
        text.draw()
    
    def update(dt):
        pass
    
    if __name__ == "__main__":
        pyglet.clock.schedule_interval(update, 1.0/60)
        pyglet.app.run()