Window Management tcod.context#

This module is used to create and handle libtcod contexts.

See Getting Started for beginner examples on how to use this module.

Context’s are intended to replace several libtcod functions such as libtcodpy.console_init_root, libtcodpy.console_flush, tcod.console.recommended_size, and many other functions which rely on hidden global objects within libtcod. If you begin using contexts then most of these functions will no longer work properly.

Instead of calling libtcodpy.console_init_root you can call with different keywords depending on how you plan to setup the size of the console. You should use tcod.tileset to load the font for a context.


If you use contexts then expect deprecated functions from libtcodpy to no longer work correctly. Those functions rely on a global console or tileset which doesn’t exists with contexts. Also libtcodpy event functions will no longer return tile coordinates for the mouse.

New programs not using libtcodpy can ignore this warning.

New in version 11.12.

class tcod.context.Context(context_p: Any)[source]#

Context manager for libtcod context objects.

Use to create a new context.

__enter__() Context[source]#

Enter this context which will close on exiting.

__exit__(*_: object) None[source]#

Automatically close on the context on exit.

__reduce__() NoReturn[source]#

Contexts can not be pickled, so this class will raise pickle.PicklingError.

change_tileset(tileset: Tileset | None) None[source]#

Change the active tileset used by this context.

The new tileset will take effect on the next call to present. Contexts not using a renderer with an emulated terminal will be unaffected by this method.

This does not do anything to resize the window, keep this in mind if the tileset as a differing tile size. Access the window with sdl_window to resize it manually, if needed.

Using this method only one tileset is active per-frame. See tcod.render if you want to renderer with multiple tilesets in a single frame.

close() None[source]#

Close this context, closing any windows opened by this context.

Afterwards doing anything with this instance other than closing it again is invalid.

convert_event(event: _Event) _Event[source]#

Return an event with mouse pixel coordinates converted into tile coordinates.


context: tcod.context.Context
for event in tcod.event.get():
    event_tile = context.convert_event(event)
    if isinstance(event, tcod.event.MouseMotion):
        # Events start with pixel coordinates and motion.
        print(f"Pixels: {event.position=}, {event.motion=}")
    if isinstance(event_tile, tcod.event.MouseMotion):
        # Tile coordinates are used in the returned event.
        print(f"Tiles: {event_tile.position=}, {event_tile.motion=}")

Changed in version 15.0: Now returns a new event with the coordinates converted into tiles.

new_console(min_columns: int = 1, min_rows: int = 1, magnification: float = 1.0, order: Literal['C', 'F'] = 'C') Console[source]#

Return a new console sized for this context.

min_columns and min_rows are the minimum size to use for the new console.

magnification determines the apparent size of the tiles on the output display. A magnification larger then 1.0 will output smaller consoles, which will show as larger tiles when presented. magnification must be greater than zero.

order is passed to tcod.console.Console to determine the memory order of its NumPy attributes.

The times where it is the most useful to call this method are:

  • After the context is created, even if the console was given a specific size.

  • After the change_tileset method is called.

  • After any window resized event, or any manual resizing of the window.

New in version 11.18.

Changed in version 11.19: Added order parameter.


scale = 1  # Tile size scale.  This example uses integers but floating point numbers are also valid.
context =
while True:
    # Create a cleared, dynamically-sized console for each frame.
    console = context.new_console(magnification=scale)
    # This printed output will wrap if the window is shrunk.
    console.print_box(0, 0, console.width, console.height, "Hello world")
    # Use integer_scaling to prevent subpixel distortion.
    # This may add padding around the rendered console.
    context.present(console, integer_scaling=True)
    for event in tcod.event.wait():
        if isinstance(event, tcod.event.Quit):
            raise SystemExit()
        elif isinstance(event, tcod.event.MouseWheel):
            # Use the mouse wheel to change the rendered tile size.
            scale = max(1, scale + event.y)
pixel_to_subtile(x: int, y: int) tuple[float, float][source]#

Convert window pixel coordinates to sub-tile coordinates.

pixel_to_tile(x: int, y: int) tuple[int, int][source]#

Convert window pixel coordinates to tile coordinates.

present(console: Console, *, keep_aspect: bool = False, integer_scaling: bool = False, clear_color: tuple[int, int, int] = (0, 0, 0), align: tuple[float, float] = (0.5, 0.5)) None[source]#

Present a console to this context’s display.

console is the console you want to present.

If keep_aspect is True then the console aspect will be preserved with a letterbox. Otherwise the console will be stretched to fill the screen.

If integer_scaling is True then the console will be scaled in integer increments. This will have no effect if the console must be shrunk. You can use tcod.console.recommended_size to create a console which will fit the window without needing to be scaled.

clear_color is an RGB tuple used to clear the screen before the console is presented, this will affect the border/letterbox color.

align is an (x, y) tuple determining where the console will be placed when letter-boxing exists. Values of 0 will put the console at the upper-left corner. Values of 0.5 will center the console.

recommended_console_size(min_columns: int = 1, min_rows: int = 1) tuple[int, int][source]#

Return the recommended (columns, rows) of a console for this context.

min_columns, min_rows are the lowest values which will be returned.

If result is only used to create a new console then you may want to call Context.new_console instead.

save_screenshot(path: str | None = None) None[source]#

Save a screen-shot to the given file path.

property renderer_type: int#

Return the libtcod renderer type used by this context.

property sdl_atlas: SDLTilesetAtlas | None#

Return a tcod.render.SDLTilesetAtlas referencing libtcod’s SDL texture atlas if it exists.

New in version 13.5.

property sdl_renderer: Renderer | None#

Return a tcod.sdl.render.Renderer referencing this contexts SDL renderer if it exists.

New in version 13.4.

property sdl_window: Window | None#

Return a referencing this contexts SDL window if it exists.


import tcod

def toggle_fullscreen(context: tcod.context.Context) -> None:
    """Toggle a context window between fullscreen and windowed modes."""
    window = context.sdl_window
    if not window:
    if window.fullscreen:
        window.fullscreen = False
        window.fullscreen =

New in version 13.4.

property sdl_window_p: Any#

A cffi SDL_Window* pointer. This pointer might be NULL.

This pointer will become invalid if the context is closed or goes out of scope.

Python-tcod’s FFI provides most SDL functions. So it’s possible for anyone with the SDL2 documentation to work directly with SDL’s pointers.


import tcod

def toggle_fullscreen(context: tcod.context.Context) -> None:
    """Toggle a context window between fullscreen and windowed modes."""
    if not context.sdl_window_p:
    fullscreen = tcod.lib.SDL_GetWindowFlags(context.sdl_window_p) & (
        0 if fullscreen else tcod.lib.SDL_WINDOW_FULLSCREEN_DESKTOP,
    )*, x: int | None = None, y: int | None = None, width: int | None = None, height: int | None = None, columns: int | None = None, rows: int | None = None, renderer: int | None = None, tileset: Tileset | None = None, vsync: bool = True, sdl_window_flags: int | None = None, title: str | None = None, argv: Iterable[str] | None = None, console: Console | None = None) Context[source]#

Create a new context with the desired pixel size.

x, y, width, and height are the desired position and size of the window. If these are None then they will be derived from columns and rows. So if you plan on having a console of a fixed size then you should set columns and rows instead of the window keywords.

columns and rows is the desired size of the console. Can be left as None when you’re setting a context by a window size instead of a console.

console automatically fills in the columns and rows parameters from an existing tcod.console.Console instance.

Providing no size information at all is also acceptable.

renderer now does nothing and should not be set. It may be removed in the future.

tileset is the font/tileset for the new context to render with. The fall-back tileset available from passing None is useful for prototyping, but will be unreliable across platforms.

vsync is the Vertical Sync option for the window. The default of True is recommended but you may want to use False for benchmarking purposes.

sdl_window_flags is a bit-field of SDL window flags, if None is given then a default of tcod.context.SDL_WINDOW_RESIZABLE is used. There’s more info on the SDL documentation:

title is the desired title of the window.

argv these arguments are passed to libtcod and allow an end-user to make last second changes such as forcing fullscreen or windowed mode, or changing the libtcod renderer. By default this will pass in sys.argv but you can disable this feature by providing an empty list instead. Certain commands such as -help will raise a SystemExit exception from this function with the output message.

When a window size is given instead of a console size then you can use Context.recommended_console_size to automatically find the size of the console which should be used.

New in version 11.16.

Changed in version 13.2: Added the console parameter.

tcod.context.new_terminal(columns: int, rows: int, *, renderer: int | None = None, tileset: Tileset | None = None, vsync: bool = True, sdl_window_flags: int | None = None, title: str | None = None) Context[source]#

Create a new context with the desired console size.

Deprecated since version 11.16: provides more options.

tcod.context.new_window(width: int, height: int, *, renderer: int | None = None, tileset: Tileset | None = None, vsync: bool = True, sdl_window_flags: int | None = None, title: str | None = None) Context[source]#

Create a new context with the desired pixel size.

Deprecated since version 11.16: provides more options, such as window position.

tcod.context.RENDERER_OPENGL = 1#

A renderer for older versions of OpenGL.

Should support OpenGL 1 and GLES 1

tcod.context.RENDERER_OPENGL2 = 4#

An SDL2/OPENGL2 renderer. Usually faster than regular SDL2.

Recommended if you need a high performance renderer.

Should support OpenGL 2.0 and GLES 2.0.

tcod.context.RENDERER_SDL = 2#

Same as RENDERER_SDL2, but forces SDL2 into software mode.

tcod.context.RENDERER_SDL2 = 3#

The main SDL2 renderer.

Rendering is decided by SDL2 and can be changed by using an SDL2 hint:

tcod.context.RENDERER_XTERM = 5#

A renderer targeting modern terminals with 24-bit color support.

This is an experimental renderer with partial support for XTerm and SSH. This will work best on those terminals.

Terminal inputs and events will be passed to SDL’s event system.

There is poor support for ANSI escapes on Windows 10. It is not recommended to use this renderer on Windows.

New in version 13.3.

tcod.context.SDL_WINDOW_ALLOW_HIGHDPI = 8192#

High DPI mode, see the SDL documentation.

tcod.context.SDL_WINDOW_BORDERLESS = 16#

Window has no decorative border.

tcod.context.SDL_WINDOW_FULLSCREEN = 1#

Exclusive fullscreen mode.

It’s generally not recommended to use this flag unless you know what you’re doing. SDL_WINDOW_FULLSCREEN_DESKTOP should be used instead whenever possible.


A borderless fullscreen window at the desktop resolution.

tcod.context.SDL_WINDOW_HIDDEN = 8#

Window is hidden.

tcod.context.SDL_WINDOW_INPUT_GRABBED = 256#

Window has grabbed the input.

tcod.context.SDL_WINDOW_MAXIMIZED = 128#

Window is maximized.

tcod.context.SDL_WINDOW_MINIMIZED = 64#

Window is minimized.

tcod.context.SDL_WINDOW_RESIZABLE = 32#

Window can be resized.