CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-pyglet

Cross-platform windowing and multimedia library for Python with OpenGL graphics, event handling, and audio/video playback

Overview
Eval results
Files

text-rendering.mddocs/

Text Rendering

Font loading, text labels, layouts, and editing with caret support.

Quick Reference

# Load font
font = pyglet.font.load('Arial', 16, bold=False, italic=False)
pyglet.font.add_file('custom.ttf')  # Add custom font

# Simple label
label = pyglet.text.Label(
    'Hello World',
    font_name='Arial', font_size=16,
    x=10, y=10,
    color=(255, 255, 255, 255),
    batch=batch
)

# HTML text
doc = pyglet.text.decode_html('<b>Bold</b> and <i>italic</i>')
layout = pyglet.text.layout.TextLayout(doc, width=200, height=100)

Font Loading

def pyglet.font.load(name=None, size=None, weight='normal',
                     italic=False, stretch=False, dpi=None):
    """
    Args:
        name: Font family name or list of names (None = default)
        size: Font size in points (None = 12)
        weight: 'normal', 'bold', 'light', etc.
        italic: True/False or 'oblique'
        stretch: True/False or 'condensed', 'expanded'
        dpi: DPI for size calculation (default: 96)
    """

def pyglet.font.add_file(font: str | BinaryIO | bytes):
    """Add font file to search path"""

def pyglet.font.add_directory(directory: str):
    """Add directory of .ttf files"""

def pyglet.font.have_font(name: str) -> bool:
    """Check if font available"""

Text Label

class pyglet.text.Label:
    __init__(text='', font_name=None, font_size=None, weight='normal',
             italic=False, color=(255,255,255,255), x=0, y=0,
             width=None, height=None, anchor_x='left', anchor_y='baseline',
             align='left', multiline=False, dpi=None, batch=None, group=None)

    # Properties
    text: str
    font_name: str
    font_size: float
    bold, italic: bool
    color: tuple  # RGBA (0-255)
    x, y: float
    width, height: float | None
    anchor_x: str  # 'left', 'center', 'right'
    anchor_y: str  # 'top', 'center', 'baseline', 'bottom'
    multiline: bool

    # Methods
    def draw()

Anchor Points:

  • anchor_x: 'left', 'center', 'right'
  • anchor_y: 'top', 'center', 'baseline', 'bottom'

Alignment (multiline):

  • align: 'left', 'center', 'right'

Text Layouts

# Basic layout
layout = pyglet.text.layout.TextLayout(document, width=None, height=None,
                                        multiline=False, dpi=None, batch=None, group=None)

# Scrollable layout
layout = pyglet.text.layout.ScrollableTextLayout(document, width, height,
                                                  multiline=False, dpi=None, batch=None, group=None)

# Incremental layout (large documents)
layout = pyglet.text.layout.IncrementalTextLayout(document, width, height,
                                                   multiline=False, dpi=None, batch=None, group=None)

HTML Text

# Decode HTML
document = pyglet.text.decode_html(html_string, location=None)

# Decode HTML from file
with open('text.html') as f:
    document = pyglet.text.decode_html(f.read())

# Supported tags: <b>, <i>, <u>, <font>, <br>, <p>, <span>
html = '''
<font face="Arial" size="16" color="#FF0000">
    <b>Bold red text</b><br/>
    <i>Italic text</i>
</font>
'''
document = pyglet.text.decode_html(html)
layout = pyglet.text.layout.TextLayout(document, width=400, height=200)
layout.x = 10
layout.y = 10

@window.event
def on_draw():
    window.clear()
    layout.draw()

Text Editing with Caret

# Create editable text
document = pyglet.text.document.UnformattedDocument('Edit me')
layout = pyglet.text.layout.IncrementalTextLayout(document, width=400, height=200)
caret = pyglet.text.caret.Caret(layout)

# Attach to window
layout.x = 10
layout.y = 10
window.push_handlers(caret)

@window.event
def on_draw():
    window.clear()
    layout.draw()

# Caret properties
caret.visible: bool
caret.position: int  # Character index
caret.mark: int | None  # Selection start (None = no selection)
caret.color: tuple  # RGB

# Caret methods
caret.select_all()
caret.select_word()
caret.select_paragraph()
caret.delete_selection()
caret.move_to_point(x, y)

Examples

Centered Text

label = pyglet.text.Label(
    'Centered Text',
    font_name='Arial',
    font_size=24,
    x=window.width // 2,
    y=window.height // 2,
    anchor_x='center',
    anchor_y='center'
)

Multiline Text

label = pyglet.text.Label(
    'Line 1\nLine 2\nLine 3',
    font_name='Arial',
    font_size=16,
    x=10, y=window.height - 10,
    width=200,
    multiline=True,
    anchor_y='top'
)

Animated Text Color

label = pyglet.text.Label('Pulsing Text', font_size=24, x=100, y=100)

def update(dt):
    import math
    intensity = int(128 + 127 * math.sin(pyglet.clock.get_default().time() * 2))
    label.color = (intensity, intensity, 255, 255)

pyglet.clock.schedule(update)

Text with Shadow

batch = pyglet.graphics.Batch()
bg_group = pyglet.graphics.Group(order=0)
fg_group = pyglet.graphics.Group(order=1)

# Shadow (behind)
shadow = pyglet.text.Label(
    'Text with Shadow', font_size=24,
    x=102, y=98, color=(0, 0, 0, 128),
    batch=batch, group=bg_group
)

# Main text (front)
text = pyglet.text.Label(
    'Text with Shadow', font_size=24,
    x=100, y=100, color=(255, 255, 255, 255),
    batch=batch, group=fg_group
)

@window.event
def on_draw():
    window.clear()
    batch.draw()

Performance Tips

  1. Use batch rendering: Add labels to Batch
  2. Avoid frequent text changes: Cache labels when possible
  3. Use appropriate layout: TextLayout for simple, IncrementalTextLayout for large/dynamic
  4. Preload fonts: Call pyglet.font.load() during initialization
  5. Limit multiline width: Large widths slow down wrapping

Common Issues

  1. Font not found: Check name with pyglet.font.have_font()
  2. Text position: Remember (0,0) is bottom-left
  3. Multiline wrapping: Requires width parameter
  4. Color format: RGBA values are 0-255, not 0.0-1.0
  5. Anchor point: Affects where (x,y) is relative to text

Install with Tessl CLI

npx tessl i tessl/pypi-pyglet@2.1.1

docs

3d-models.md

app-clock.md

audio-video.md

graphics-rendering.md

gui.md

images-textures.md

index.md

input-devices.md

math.md

opengl.md

resource-management.md

sprites-shapes.md

text-rendering.md

windowing.md

tile.json