pyglet - 检索标签的宽度

pyglet - Retrieve width of Label

我有一个用于在屏幕上显示文本的标签元素:

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

有了标签我还有一个pyglet.sprite.Sprite:

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

这个精灵的图像是 1x1 像素,我使用 scale_x 和 scale_y 值绘制一个矩形。

我想将这个 sprite 的宽度设置为文本的宽度,以便文本适合它。

我试过使用 Label.width:

sprite.scale_x = nameLabel.width

但是,宽度仅返回 None,因此引发错误。

我想不出任何其他方法来检索此标签的宽度。有谁知道我该怎么做?

谢谢,

大卫.

我认为您应该使用内容宽度和内容高度属性。它应该 return 标签矩形的宽度和高度。

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()