pyglet.window
Submodules
Details
Windowing and user-interface events.
This module allows applications to create and display windows with a graphical context. Windows can be created with a variety of border styles or set fullscreen.
You can register event handlers for keyboard, mouse and window events. For games and kiosks you can also restrict the input to your windows, for example disabling users from switching away from the application with certain key combinations or capturing and hiding the mouse.
Getting started
Call the Window constructor to create a new window:
from pyglet.window import Window
win = Window(width=960, height=540)
Attach your own event handlers:
@win.event
def on_key_press(symbol, modifiers):
# ... handle this event ...
Place drawing code for the window within the Window.on_draw event handler:
@win.event
def on_draw():
# ... drawing code ...
Call pyglet.app.run to enter the main event loop (by default, this returns when all open windows are closed):
from pyglet import app
app.run()
Creating a game window
Use set_exclusive_mouse()
to hide the mouse
cursor and receive relative mouse movement events. Specify fullscreen=True
as a keyword argument to the Window
constructor to
render to the entire screen rather than opening a window:
win = Window(fullscreen=True)
win.set_exclusive_mouse()
Working with multiple screens
By default, fullscreen windows are opened on the primary display (typically set by the user in their operating system settings). You can retrieve a list of attached screens and select one manually if you prefer. This is useful for opening a fullscreen window on each screen:
display = pyglet.display.get_display()
screens = display.get_screens()
windows = []
for screen in screens:
windows.append(window.Window(fullscreen=True, screen=screen))
Specifying a screen has no effect if the window is not fullscreen.
Specifying the Graphical context properties
Each window has its own context which is created when the window is created. You can specify the properties of the context before it is created by creating a “template” configuration:
from pyglet.graphics.api import get_config
# Create template config
config = get_config()
config.stencil_size = 8
config.aux_buffers = 4
# Create a window using this config
win = window.Window(config=config)
To determine if a given configuration is supported, query the screen (see above, “Working with multiple screens”):
configs = screen.get_matching_configs(config)
if not configs:
# ... config is not supported
else:
win = window.Window(config=configs[0])
Classes
- class Window
Bases:
EventDispatcher
Platform-independent application window.
A window is a “heavyweight” object occupying operating system resources. The “client” or “content” area of a window is filled entirely with a graphical API’s viewport, if enabled. Applications have no access to operating system widgets or controls; all rendering must be done via a graphical API backend.
Windows may appear as floating regions or can be set to fill an entire screen (fullscreen). When floating, windows may appear borderless or decorated with a platform-specific frame (including, for example, the title bar, minimize and close buttons, resize handles, and so on).
While it is possible to set the location of a window, it is recommended that applications allow the platform to place it according to local conventions. This will ensure it is not obscured by other windows, and appears on an appropriate screen for the user.
For OpenGL, to render into a window, you must first call its
switch_to()
method to make it the active OpenGL context. If you use only one window in your application, you can skip this step as it will always be the active context.Methods
- abstract activate() None
Attempt to restore keyboard focus to the window.
Depending on the window manager or operating system, this may not be successful. For example, on Windows XP an application is not allowed to “steal” focus from another application. Instead, the window’s taskbar icon will flash, indicating it requires attention.
- Return type:
- clear() None
Clear the window.
This is a convenience method for clearing the color and depth buffer. The window must be the active context (see
switch_to()
).- Return type:
- close() None
Close the window.
After closing the window, the GL context will be invalid. The window instance cannot be reused once closed. To re-use windows, see
set_visible()
instead.The
pyglet.app.EventLoop.on_window_close()
event is dispatched by thepyglet.app.event_loop
when this method is called.- Return type:
- dispatch_event(*args: Any) None
Dispatch an event to the attached event handlers.
The event is propagated to all registered event handlers in the stack, starting and the top and going down. If any registered event handler returns
EVENT_HANDLED
, no further handlers down the stack will receive this event.This method has several possible return values. If any event hander has returned
EVENT_HANDLED
, then this method will also returnEVENT_HANDLED
. If not, this method will returnEVENT_UNHANDLED
. If there were no events registered to receive this event,False
is returned.- Return type:
- Returns:
EVENT_HANDLED
if any event handler returnedEVENT_HANDLED
;EVENT_UNHANDLED
if one or more event handlers were invoked without any of them returning EVENT_HANDLED;False
if no event handlers were registered.
- abstract dispatch_events() None
Poll the operating system event queue for new events and call attached event handlers.
This method is provided for legacy applications targeting pyglet 1.0, and advanced applications that must integrate their event loop into another framework.
Typical applications should use
pyglet.app.run()
.- Return type:
- draw_mouse_cursor() None
Draw the custom mouse cursor.
If the current mouse cursor has
drawable
set, this method is called before the buffers are flipped to render it.There is little need to override this method; instead, subclass
MouseCursor
and provide your owndraw()
method.- Return type:
- abstract flip() None
Swap the front and back buffers.
Call this method on a double-buffered window to update the visible display with the back buffer. Windows are double-buffered by default unless you turn this feature off.
The contents of the back buffer are undefined after this operation.
The default
event_loop
automatically calls this method after the window’son_draw()
event.- Return type:
- get_framebuffer_size() tuple[int, int]
Return the size in actual pixels of the Window framebuffer.
When using HiDPI screens, the size of the Window’s framebuffer can be higher than that of the Window size requested. If you are performing operations that require knowing the actual number of pixels in the window, this method should be used instead of
Window.get_size()
. For example, setting the Window projection or setting the glViewport size.
- get_pixel_ratio() float
Return the framebuffer/window size ratio.
Some platforms and/or window systems support subpixel scaling, making the framebuffer size larger than the window size. Retina screens on OS X and Gnome on Linux are some examples.
On a Retina systems the returned ratio would usually be 2.0 as a window of size 500 x 500 would have a framebuffer of 1000 x 1000. Fractional values between 1.0 and 2.0, as well as values above 2.0 may also be encountered.
- Deprecated:
Use Window.scale.
- Return type:
- get_size() tuple[int, int]
Return the current size of the window.
This does not include the windows’ border or title bar.
- get_system_mouse_cursor(name: str) MouseCursor
Obtain a system mouse cursor.
Use
set_mouse_cursor()
to make the cursor returned by this method active. The names accepted by this method are theCURSOR_*
constants defined on this class.- Return type:
- abstract maximize() None
Maximize the window.
The behaviour of this method is somewhat dependent on the user’s display setup. On a multi-monitor system, the window may maximize to either a single screen or the entire virtual desktop.
- Return type:
- abstract set_caption(caption: str) None
Set the window’s caption.
The caption appears in the titlebar of the window, if it has one, and in the taskbar on Windows and many X11 window managers.
- Return type:
- set_exclusive_keyboard(exclusive: bool = True) None
Prevent the user from switching away from this window using keyboard accelerators.
When enabled, this feature disables certain operating-system specific key combinations such as Alt+Tab (Command+Tab on OS X). This can be useful in certain kiosk applications, it should be avoided in general applications or games.
- Return type:
- set_exclusive_mouse(exclusive: bool = True) None
Hide the mouse cursor and direct all mouse events to this window.
When enabled, this feature prevents the mouse leaving the window. It is useful for certain styles of games that require complete control of the mouse. The position of the mouse as reported in subsequent events is meaningless when exclusive mouse is enabled; you should only use the relative motion parameters
dx
anddy
.- Return type:
- set_fullscreen(
- fullscreen: bool = True,
- screen: Screen | None = None,
- mode: ScreenMode | None = None,
- width: int | None = None,
- height: int | None = None,
Toggle to or from fullscreen.
After toggling fullscreen, the GL context should have retained its state and objects, however the buffers will need to be cleared and redrawn.
If
width
andheight
are specified andfullscreen
is True, the screen may be switched to a different resolution that most closely matches the given size. If the resolution doesn’t match exactly, a higher resolution is selected and the window will be centered within a black border covering the rest of the screen.- Parameters:
fullscreen (
bool
) – True if the window should be made fullscreen, False if it should be windowed.screen (
Screen
|None
) – If not None and fullscreen is True, the window is moved to the given screen. The screen must belong to the same display as the window.mode (
ScreenMode
|None
) – The screen will be switched to the given mode. The mode must have been obtained by enumeratingget_modes()
. If None, an appropriate mode will be selected from the givenwidth
andheight
.int Optional width of the window. If unspecified, defaults to the previous window size when windowed, or the screen size if fullscreen.
New in version 1.2.
Optional height of the window. If unspecified, defaults to the previous window size when windowed, or the screen size if fullscreen.
New in version 1.2.
- Return type:
- set_icon(*images: AbstractImage) None
Set the window icon.
If multiple images are provided, one with an appropriate size will be selected (if the correct size is not provided, the image will be scaled).
Useful sizes to provide are 16x16, 32x32, 64x64 (Mac only) and 128x128 (Mac only).
- Return type:
- set_maximum_size(width: int, height: int) None
Set the maximum size of the window.
Once set, the user will not be able to resize the window larger than the given dimensions. There is no way to remove the maximum size constraint on a window (but you could set it to a large value).
The behaviour is undefined if the maximum size is set smaller than the current size of the window.
The window size does not include the border or title bar.
- set_minimum_size(width: int, height: int) None
Set the minimum size of the window.
Once set, the user will not be able to resize the window smaller than the given dimensions. There is no way to remove the minimum size constraint on a window (but you could set it to 0,0).
The behaviour is undefined if the minimum size is set larger than the current size of the window.
The window size does not include the border or title bar.
- set_mouse_cursor(cursor: MouseCursor | None = None) None
Change the appearance of the mouse cursor.
The appearance of the mouse cursor is only changed while it is within this window.
- Parameters:
cursor (
MouseCursor
|None
) – The cursor to set, orNone
to restore the default cursor.- Return type:
- set_mouse_platform_visible(platform_visible: bool | None = None) None
Set the platform-drawn mouse cursor visibility.
This is called automatically after changing the mouse cursor or exclusive mode.
Applications should not normally need to call this method.
- See:
set_mouse_visible()
instead.- Parameters:
platform_visible (
bool
|None
) – IfNone
, sets platform visibility to the required visibility for the current exclusive mode and cursor type. Otherwise, a bool value will override and force a visibility.- Return type:
- set_mouse_visible(visible: bool = True) None
Show or hide the mouse cursor.
The mouse cursor will only be hidden while it is positioned within this window. Mouse events will still be processed as usual.
- Return type:
- set_size(width: int, height: int) None
Resize the window.
The behaviour is undefined if the window is not resizable, or if it is currently fullscreen.
The window size does not include the border or title bar.
- Return type:
- abstract switch_to() None
Make this window the current rendering context.
Only one OpenGL context can be active at a time. This method sets the current window context as the active one.
In most cases, you should use this method instead of directly calling
set_current()
. The latter will not perform platform-specific state management tasks for you.- Return type:
Events
- on_activate() Literal[True] | None
The window was activated.
This event can be triggered by clicking on the title bar, bringing it to the foreground; or by some platform-specific method.
When a window is “active” it has the keyboard focus.
- on_close() Literal[True] | None
The user attempted to close the window.
This event can be triggered by clicking on the “X” control box in the window title bar, or by some other platform-dependent manner.
The default handler sets has_exit to
True
. In pyglet 1.1, if pyglet.app.event_loop is being used, close is also called, closing the window immediately.
- on_context_lost() Literal[True] | None
The window’s GL context was lost.
When the context is lost no more GL methods can be called until it is recreated. This is a rare event, triggered perhaps by the user switching to an incompatible video mode. When it occurs, an application will need to reload all objects (display lists, texture objects, shaders) as well as restore the GL state.
- on_context_state_lost() Literal[True] | None
The state of the window’s GL context was lost.
pyglet may sometimes need to recreate the window’s GL context if the window is moved to another video device, or between fullscreen or windowed mode. In this case it will try to share the objects (display lists, texture objects, shaders) between the old and new contexts. If this is possible, only the current state of the GL context is lost, and the application should simply restore state.
- on_deactivate() Literal[True] | None
The window was deactivated.
This event can be triggered by clicking on another application window. When a window is deactivated it no longer has the keyboard focus.
- on_draw() Literal[True] | None
The window contents should be redrawn.
The EventLoop will dispatch this event when the draw method has been called. The window will already have the GL context, so there is no need to call switch_to. The window’s flip method will be called immediately after this event, so your event handler should not.
You should make no assumptions about the window contents when this event is triggered; a resize or expose event may have invalidated the framebuffer since the last time it was drawn.
- on_expose() Literal[True] | None
A portion of the window needs to be redrawn.
This event is triggered when the window first appears, and any time the contents of the window is invalidated due to another window obscuring it.
There is no way to determine which portion of the window needs redrawing. Note that the use of this method is becoming increasingly uncommon, as newer window managers composite windows automatically and keep a backing store of the window contents.
- on_file_drop(x: int, y: int, paths: list[str]) Literal[True] | None
File(s) were dropped into the window.
- Parameters:
- Return type:
New in version 1.5.1.
- Event:
- on_hide() Literal[True] | None
The window was hidden.
This event is triggered when a window is minimised or hidden by the user.
- on_key_press(symbol: int, modifiers: int) Literal[True] | None
A key on the keyboard was pressed (and held down).
Since pyglet 1.1 the default handler dispatches the
on_close()
event if theESC
key is pressed.
- on_key_release(symbol: int, modifiers: int) Literal[True] | None
A key on the keyboard was released.
- on_mouse_drag( ) Literal[True] | None
The mouse was moved with one or more mouse buttons pressed.
This event will continue to be fired even if the mouse leaves the window, so long as the drag buttons are continuously held down.
- Parameters:
x (
int
) – Distance in pixels from the left edge of the window.y (
int
) – Distance in pixels from the bottom edge of the window.dx (
int
) – Relative X position from the previous mouse position.dy (
int
) – Relative Y position from the previous mouse position.buttons (
int
) – Bitwise combination of the mouse buttons currently pressed.modifiers (
int
) – Bitwise combination of any keyboard modifiers currently active.
- Event:
- Return type:
- on_mouse_enter(x: int, y: int) Literal[True] | None
The mouse was moved into the window.
This event will not be triggered if the mouse is currently being dragged.
- on_mouse_leave(x: int, y: int) Literal[True] | None
The mouse was moved outside the window.
This event will not be triggered if the mouse is currently being dragged.
- Event:
- on_mouse_motion( ) Literal[True] | None
The mouse was moved with no buttons held down.
- Parameters:
- Event:
- Return type:
- on_mouse_press( ) Literal[True] | None
A mouse button was pressed (and held down).
- Parameters:
- Event:
- Return type:
- on_mouse_release( ) Literal[True] | None
A mouse button was released.
- Parameters:
- Event:
- Return type:
- on_mouse_scroll( ) Literal[True] | None
The mouse wheel was scrolled.
Note that most mice have only a vertical scroll wheel, so scroll_x is usually 0. An exception to this is the Apple Mighty Mouse, which has a mouse ball in place of the wheel which allows both
scroll_x
andscroll_y
movement.- Parameters:
- Event:
- Return type:
- on_move(x: int, y: int) Literal[True] | None
The window was moved.
- Parameters:
- Return type:
- Event:
- on_refresh(dt: float) Literal[True] | None
The window contents should be redrawn.
The
EventLoop
will dispatch this event when thedraw
method has been called. The window will already have the GL context, so there is no need to callswitch_to()
. The window’sflip()
method will be called immediately after this event, so your event handler should not.You should make no assumptions about the window contents when this event is triggered; a resize or expose event may have invalidated the framebuffer since the last time it was drawn. :rtype:
Literal
[True
] |None
New in version 2.0.
- Event:
- on_resize(width: int, height: int) Literal[True] | None
The window was resized.
The window will have the GL context when this event is dispatched; there is no need to call
switch_to()
in this handler.
- on_show() Literal[True] | None
The window was shown.
This event is triggered when a window is restored after being minimised, hidden, or after being displayed for the first time.
- on_text(text: str) Literal[True] | None
The user input some text.
Typically, this is called after
on_key_press()
and beforeon_key_release()
, but may also be called multiple times if the key is held down (key repeating); or called without key presses if another input method was used (e.g., a pen input).You should always use this method for interpreting text, as the key symbols often have complex mappings to their unicode representation which this event takes care of.
- on_text_motion(motion: int) Literal[True] | None
The user moved the text input cursor.
Typically this is called after
on_key_press()
and beforeon_key_release()
, but may also be called multiple times if the key is help down (key repeating).You should always use this method for moving the text input cursor (caret), as different platforms have different default keyboard mappings, and key repeats are handled correctly.
The values that motion can take are defined in
pyglet.window.key
: :rtype:Literal
[True
] |None
MOTION_UP
MOTION_RIGHT
MOTION_DOWN
MOTION_LEFT
MOTION_NEXT_WORD
MOTION_PREVIOUS_WORD
MOTION_BEGINNING_OF_LINE
MOTION_END_OF_LINE
MOTION_NEXT_PAGE
MOTION_PREVIOUS_PAGE
MOTION_BEGINNING_OF_FILE
MOTION_END_OF_FILE
MOTION_BACKSPACE
MOTION_DELETE
- Event:
- on_text_motion_select(motion: int) Literal[True] | None
The user moved the text input cursor while extending the selection.
Typically this is called after
on_key_press()
and beforeon_key_release()
, but may also be called multiple times if the key is help down (key repeating).You should always use this method for responding to text selection events rather than the raw
on_key_press()
, as different platforms have different default keyboard mappings, and key repeats are handled correctly.The values that motion can take are defined in
pyglet.window.key
: :rtype:Literal
[True
] |None
MOTION_UP
MOTION_RIGHT
MOTION_DOWN
MOTION_LEFT
MOTION_NEXT_WORD
MOTION_PREVIOUS_WORD
MOTION_BEGINNING_OF_LINE
MOTION_END_OF_LINE
MOTION_NEXT_PAGE
MOTION_PREVIOUS_PAGE
MOTION_BEGINNING_OF_FILE
MOTION_END_OF_FILE
- Event:
Attributes
- aspect_ratio
The aspect ratio of the window. Read-Only.
- caption
The window caption (title). Read-only.
- config
A graphical config describing the context of this window. Read-only.
- context
The graphical context attached to this window. Read-only.
- display
The display this window belongs to. Read-only.
- dpi
DPI values of the Window.
Read only.
- fullscreen
True if the window is currently fullscreen. Read-only.
- height
The height of the window, in pixels. Read-write.
- projection
The window projection matrix. Read-write.
This matrix is used to transform vertices when using any of the built-in drawable classes. view is done first, then projection.
The default projection matrix is orthographic (2D), but a custom
Mat4
instance can be set. Alternatively, you can supply a flat tuple of 16 values.(2D), but can be changed to any 4x4 matrix desired. :see:
Mat4
.
- resizeable
True if the window is resizable. Read-only.
- scale
The scale of the window factoring in DPI.
Read only.
- screen
The screen this window is fullscreen in. Read-only.
- size
The size of the window. Read-Write.
- style
The window style; one of the
WINDOW_STYLE_*
constants. Read-only.
- view
The window view matrix. Read-write.
This matrix is used to transform vertices when using any of the built-in drawable classes. view is done first, then projection.
The default view is an identity matrix, but a custom
Mat4
instance can be set. Alternatively, you can supply a flat tuple of 16 values.
- viewport
The Window viewport.
The Window viewport, expressed as (x, y, width, height).
- visible
True if the window is currently visible. Read-only.
- vsync
True if buffer flips are synchronised to the screen’s vertical retrace. Read-only.
- width
The width of the window, in pixels. Read-write.
Class attributes: cursor names
- CURSOR_DEFAULT = None
Class attributes: window styles
- __init__(
- width: int | None = None,
- height: int | None = None,
- caption: str | None = None,
- resizable: bool = False,
- style: str | None = None,
- fullscreen: bool = False,
- visible: bool = True,
- vsync: bool = True,
- file_drops: bool = False,
- display: Display | None = None,
- screen: Screen | None = None,
- config: GraphicsConfig | None = None,
- context: WindowGraphicsContext | None = None,
- mode: ScreenMode | None = None,
Create a window.
All parameters are optional, and reasonable defaults are assumed where they are not specified.
The
display
,screen
,config
andcontext
parameters form a hierarchy of control: there is no need to specify more than one of these. For example, if you specifyscreen
thedisplay
will be inferred, and a defaultconfig
andcontext
will be created.config
is a special case; it can be a template created by the user specifying the attributes desiredThe context will be active as soon as the window is created, as if
switch_to`()
was just called.- Parameters:
width (
int
|None
) – Width of the window, in pixels. Defaults to 960, or the screen width iffullscreen
is True.height (
int
|None
) – Height of the window, in pixels. Defaults to 540, or the screen height iffullscreen
is True.caption (
str
|None
) – Initial caption (title) of the window. Defaults tosys.argv[0]
.resizable (
bool
) – If True, the window will be resizable. Defaults to False.style (
str
|None
) – One of theWINDOW_STYLE_*
constants specifying the border style of the window.fullscreen (
bool
) – If True, the window will cover the entire screen rather than floating. Defaults to False.visible (
bool
) – Determines if the window is visible immediately after creation. Defaults to True. Set this to False if you would like to change attributes of the window before having it appear to the user.vsync (
bool
) – If True, buffer flips are synchronised to the primary screen’s vertical retrace, eliminating flicker.file_drops (
bool
) – If True, the Window will accept files being dropped into it and call theon_file_drop
event.display (
Display
|None
) – The display device to use. Useful only under X11.screen (
Screen
|None
) – The screen to use, if in fullscreen.config (
GraphicsConfig
|None
) – Either a template from which to create a complete config, or a complete config.context (
WindowGraphicsContext
|None
) – The context to attach to this window. The context must not already be attached to another window.mode (
ScreenMode
|None
) – The screen will be switched to this mode if fullscreen is True. If None, an appropriate mode is selected to accommodatewidth
and ``height`.
- __new__(**kwargs)
- class FPSDisplay
Bases:
object
Display of a window’s framerate.
This is a convenience class to aid in profiling and debugging. Typical usage is to create an FPSDisplay for each window, and draw the display at the end of the windows’
on_draw()
event handler:from pyglet.window import Window, FPSDisplay window = Window() fps_display = FPSDisplay(window) @window.event def on_draw(): # ... perform ordinary window drawing operations ... fps_display.draw()
The style and position of the display can be modified via the
label
attribute. The display can be set to update more or less often by setting the update_period attribute.- __init__(
- window: Window,
- color: tuple[int, int, int, int] = (127, 127, 127, 127),
- batch=None,
- samples: int = 240,
Create an FPS Display.
- update() None
Records a new data point at the current time.
This method is called automatically when the window buffer is flipped.
- Return type:
- update_period = 0.25
Time in seconds between updates.
- class MouseCursor
An abstract mouse cursor.
- draw(x: int, y: int) None
Abstract render method.
The cursor should be drawn with the “hot” spot at the given coordinates. The projection is set to the pyglet default (i.e., orthographic in window-space), however no other aspects of the state can be assumed.
- class DefaultMouseCursor
Bases:
MouseCursor
The default mouse cursor set by the operating system.
- __init__()
- __new__(**kwargs)
- class ImageMouseCursor
Bases:
MouseCursor
A user-defined mouse cursor created from an image.
Use this class to create your own mouse cursors and assign them to windows. Cursors can be drawn by the graphics API, or optionally passed to the OS to render natively. There are no restrictions on cursors drawn by the graphical API, but natively rendered cursors may have some platform limitations (such as color depth, or size). In general, reasonably sized cursors will render correctly
- __init__(
- image: AbstractImage,
- hot_x: int = 0,
- hot_y: int = 0,
- acceleration: bool = False,
Create a mouse cursor from an image.
- Parameters:
image (
AbstractImage
) – Image to use for the mouse cursor. It must have a validtexture
attribute.hot_x (
int
) – X coordinate of the “hot” spot in the image relative to the image’s anchor. May be clamped to the maximum image width if acceleration is enabled.hot_y (
int
) – Y coordinate of the “hot” spot in the image, relative to the image’s anchor. May be clamped to the maximum image height if acceleration is enabled.acceleration (
bool
) – IfTrue
, draw the cursor natively instead of using the graphics API. The image may be downsampled or color reduced to fit the platform limitations.
Exceptions
- class MouseCursorException
The root exception for all mouse cursor-related errors.
- __init__(*args, **kwargs)
- __new__(**kwargs)
- class NoSuchConfigException
An exception indicating the requested configuration is not available.
- __init__(*args, **kwargs)
- __new__(**kwargs)