psychos.visual.Window#
- class psychos.visual.Window(width: int | None = None, height: int | None = None, caption: str | None = None, fullscreen: bool = False, visible: bool = True, background_color: ColorType | None = None, mouse_visible: bool = False, coordinates: UnitType | Unit = 'norm', distance: float | None = 50, inches: float | None = None, clear_after_flip: bool = True, screen: pyglet.canvas.Screen | int | None = None, **kwargs)[source]#
Bases:
HeadlessWindowCustom window for displaying visual elements.
A subclass of pyglet.window.Window, this class provides additional functionality for handling units, background color, and event management, while maintaining full compatibility with the pyglet library. For more information on pyglet, refer to the official documentation.
- Parameters:
width (Optional[int], default=None) – The width of the window in pixels or another unit type. If None, a default width is used.
height (Optional[int], default=None) – The height of the window in pixels or another unit type. If None, a default height is used.
caption (Optional[str], default=None) – The caption or title of the window. If None, no caption is displayed.
fullscreen (bool, default=False) – Indicates if the window should be displayed in fullscreen mode.
visible (bool, default=True) – Specifies whether the window is visible upon creation.
background_color (Optional[ColorType], default=None) – The background color of the window, provided as an RGB/RGBA tuple or a named color string. If None, the default color is used.
mouse_visible (bool, default=False) – Determines if the mouse cursor should be visible within the window.
units (Union[UnitType, Unit], default="norm") – The unit system for the window. Can be a string or a Unit object to manage coordinates and sizes.
distance (Optional[float], default=50) – The viewing distance from the screen in centimeters, used for visual angle calculations (e.g., degrees).
inches (Optional[float], default=None) – The diagonal size of the monitor in inches. Required for accurate DPI (dots per inch) and physical size calculations.
clear_after_flip (bool, default=True) – If True, the window will be cleared after flipping the frame buffer, preparing it for the next frame.
kwargs (dict) – Additional keyword arguments to be passed to the Pyglet window constructor.
- distance#
The viewing distance in centimeters, used for units like degrees of visual angle.
- Type:
- units#
The current unit system used to convert between different coordinate and size units.
- Type:
Examples
Basic usage for displaying visual elements:
from psychos import Window, Text # Create a new window window = Window() # Create a text stimulus and draw it text = Text("Hello, World!").draw() # Display the drawn elements on the screen window.flip() # Keep the window open for 3 seconds window.wait(3)
You can also display other elements like images:
from psychos import Window, Image from pathlib import Path # Create a new window window = Window() # Load and draw an image img_path = Path("image.png") image = Image(img_path).draw() # Flip the window to display the drawn elements window.flip() # Keep the window open for 3 seconds window.wait(3)
- __init__(width: int | None = None, height: int | None = None, caption: str | None = None, fullscreen: bool = False, visible: bool = True, background_color: ColorType | None = None, mouse_visible: bool = False, coordinates: UnitType | Unit = 'norm', distance: float | None = 50, inches: float | None = None, clear_after_flip: bool = True, screen: pyglet.canvas.Screen | int | None = None, **kwargs)[source]#
Creates an instance of the Window class.
Methods
__init__([width, height, caption, ...])Creates an instance of the Window class.
activate()Attempt to restore keyboard focus to the window.
clear()Clear the window.
close()Close the window.
dispatch_event(*args)Dispatch an event to the attached event handlers.
dispatch_events()Poll the operating system event queue for new events and call attached event handlers.
dispatch_pending_events()draw(dt)Redraw the Window contents.
draw_mouse_cursor()Draw the custom mouse cursor.
event(*args)Function decorator for an event handler.
flip([clear])Flip the window's frame buffer and optionally clear the window after.
get_clipboard_text()Access the system clipboard and attempt to retrieve text.
get_framebuffer_size()Return the size in actual pixels of the Window framebuffer.
get_location()Return the current position of the window.
get_pixel_ratio()Return the framebuffer/window size ratio.
get_requested_size()Return the size of the window without any scaling taken into effect.
get_size()Return the current size of the window.
get_system_mouse_cursor(name)Obtain a system mouse cursor.
maximize()Maximize the window.
minimize()Minimize the window.
on_close()Default on_close handler.
on_flip(func, *args, **kwargs)Register a function to be called after flipping the window's frame buffer.
on_key_press(symbol, modifiers)Default on_key_press handler.
on_resize(width, height)A default resize event handler.
on_scale(scale, dpi)A default scale event handler.
pop_handlers()Pop the top level of event handlers off the stack.
post_event(event_type, *args)Post an event to the main application thread.
push_handlers(*args, **kwargs)Push a new level onto the handler stack, and add 0 or more handlers.
register_event_type(name)Register an event type with the dispatcher.
remove_handler(name, handler)Remove a single event handler.
remove_handlers(*args, **kwargs)Remove event handlers from the event stack.
set_caption(caption)Set the window's caption.
set_clipboard_text(text)Access the system clipboard and set a text string as the clipboard data.
set_exclusive_keyboard([exclusive])Prevent the user from switching away from this window using keyboard accelerators.
set_exclusive_mouse([exclusive])Hide the mouse cursor and direct all mouse events to this window.
set_fullscreen([fullscreen, screen, mode, ...])Toggle to or from fullscreen.
set_handler(name, handler)Attach a single event handler.
set_handlers(*args, **kwargs)Attach one or more event handlers to the top level of the handler stack.
set_icon(*images)Set the window icon.
set_location(x, y)Set the position of the window.
set_maximum_size(width, height)Set the maximum size of the window.
set_minimum_size(width, height)Set the minimum size of the window.
set_mouse_cursor([cursor])Change the appearance of the mouse cursor.
set_mouse_passthrough(state)Set whether the operating system will ignore mouse input from this window.
set_mouse_platform_visible([platform_visible])Set the platform-drawn mouse cursor visibility.
set_mouse_visible([visible])Show or hide the mouse cursor.
set_size(width, height)Resize the window.
set_visible([visible])Show or hide the window.
set_vsync(vsync)Enable or disable vertical sync control.
switch_to()Make this window the current OpenGL rendering context.
wait([duration, sleep_interval, hog_period])Wait for a specified duration while dispatching window events.
wait_key([keys, modifiers, clock, max_wait, ...])Wait for a specific key event (press or release) within the given time frame.
Attributes
CURSOR_CROSSHAIRA crosshair mouse cursor.
CURSOR_DEFAULTThe default mouse cursor.
CURSOR_HANDA pointing hand mouse cursor.
CURSOR_HELPA "help" mouse cursor; typically a question mark and an arrow.
CURSOR_NOA mouse cursor indicating that the selected operation is not permitted.
CURSOR_SIZEA mouse cursor indicating the element can be resized.
CURSOR_SIZE_DOWNA mouse cursor indicating the element can be resized from the bottom border.
CURSOR_SIZE_DOWN_LEFTA mouse cursor indicating the element can be resized from the lower-left corner.
CURSOR_SIZE_DOWN_RIGHTA mouse cursor indicating the element can be resized from the lower-right corner.
CURSOR_SIZE_LEFTA mouse cursor indicating the element can be resized from the left border.
CURSOR_SIZE_LEFT_RIGHTA mouse cursor indicating the element can be resized horizontally.
CURSOR_SIZE_RIGHTA mouse cursor indicating the element can be resized from the right border.
CURSOR_SIZE_UPA mouse cursor indicating the element can be resized from the top border.
CURSOR_SIZE_UP_DOWNA mouse cursor indicating the element can be resized vertically.
CURSOR_SIZE_UP_LEFTA mouse cursor indicating the element can be resized from the upper-left corner.
CURSOR_SIZE_UP_RIGHTA mouse cursor indicating the element can be resized from the upper-right corner.
CURSOR_TEXTA text input mouse cursor (I-beam).
CURSOR_WAITA "wait" mouse cursor; typically an hourglass or watch.
CURSOR_WAIT_ARROWThe "wait" mouse cursor combined with an arrow.
WINDOW_STYLE_BORDERLESSA window style without any decoration.
WINDOW_STYLE_DEFAULTThe default window style.
WINDOW_STYLE_DIALOGThe window style for pop-up dialogs.
WINDOW_STYLE_OVERLAYA window style for transparent, topmost, click-through-able overlays
WINDOW_STYLE_TOOLThe window style for tool windows.
WINDOW_STYLE_TRANSPARENTA window style for transparent, interactable windows
aspect_ratioThe aspect ratio of the window.
Get the background color of the window (r, g, b, a).
captionThe window caption (title).
configA GL config describing the context of this window.
contextThe OpenGL context attached to this window.
Get the unit system used by the window.
displayThe display this window belongs to.
Get the number of pixels per centimeter in the window, from the monitor's size in inches.
event_typesfullscreenTrue if the window is currently fullscreen.
has_exitTrue if the user has attempted to close the window.
The height of the window, in pixels.
invalidWindow display contents validity.
projectionThe OpenGL window projection matrix.
resizeableTrue if the window is resizable.
scaleThe scale of the window factoring in DPI.
screenThe screen this window is fullscreen in.
sizeThe size of the window.
styleThe window style; one of the
WINDOW_STYLE_*constants.viewThe OpenGL window view matrix.
viewportThe Window viewport.
visibleTrue if the window is currently visible.
vsyncTrue if buffer flips are synchronised to the screen's vertical retrace.
The width of the window, in pixels.
- property background_color: Tuple[float, float, float, float] | None#
Get the background color of the window (r, g, b, a).
- property dpi: float#
Get the number of pixels per centimeter in the window, from the monitor’s size in inches.
- Returns:
The number of pixels per centimeter.
- Return type:
- flip(clear: bool | None = None) Window[source]#
Flip the window’s frame buffer and optionally clear the window after.
- Parameters:
clear (Optional[bool], default=None) – Whether to clear the window after flipping. Defaults to the value of self.clear_after_flip.
- on_flip(func, *args, **kwargs)[source]#
Register a function to be called after flipping the window’s frame buffer.
This method allows you to register a function to be called after flipping the window’s frame buffer. The function will be called with the provided arguments and keyword arguments after the flip operation is completed.
If several functions are registered, they will be called in the order they were added.
- wait(duration: float = 1, sleep_interval: float = 0.8, hog_period: float = 0.02)[source]#
Wait for a specified duration while dispatching window events.
- wait_key(keys: Iterable[str | int] | str | int | None = None, modifiers: Iterable[str | int] | str | int | None = None, clock: Clock | None = None, max_wait: float | None = None, event: Literal['press', 'release'] = 'press', clear_events: bool = True) KeyEvent[source]#
Wait for a specific key event (press or release) within the given time frame.
This function waits for a key event (either press or release) to occur, and returns the key, modifiers, and the timestamp when the event happened. It supports specifying a set of keys to listen for, or returning the first key event of any kind if no specific keys are provided. The function can also accept a timeout (max_wait), after which it will return even if no key event occurs.
If modifiers are provided, the function will check if all specified modifiers are pressed at the time of the key event. Modifiers can be ignored if modifiers is set to None, or you can enforce that no modifiers are pressed by passing an empty list.
- Parameters:
keys (Optional[Union[Iterable[Union[str, int]], str, int]]) –
The keys to wait for. It can be one of the following:
A string representing the key’s name (e.g., “SPACE”, “A”, etc.).
An integer representing the Pyglet key ID (e.g., pyglet.window.key.SPACE).
An iterable of strings or integers representing multiple keys.
If no keys are provided (keys=None), the function will return on any key press or release event.
modifiers (Optional[Union[Iterable[Union[str, int]], str, int]]) –
The modifiers to check for. It can be one of the following:
A string representing a modifier name (e.g., “CTRL”, “SHIFT”).
- An integer representing the Pyglet modifier bitmask
(e.g., pyglet.window.key.MOD_SHIFT).
An iterable of strings or integers representing multiple modifiers.
If None, the function ignores any modifiers. If an empty list is provided, the function will only return when no modifiers are pressed.
clock (Optional["Clock"]) – An optional clock object for measuring time. If not provided, the function will use time.time() from the standard library. The clock object should have a .time() method that returns the current time.
max_wait (Optional[float]) – The maximum amount of time to wait for the key event (in seconds). If this value is not provided, the function will wait indefinitely for a key event. If the timeout is reached before a key event occurs, the function returns None and the current timestamp.
event (Literal["press", "release"], default "press") – Specifies whether to wait for a key press event (“press”) or a key release event (“release”).
clear_events (bool, default True) – Whether to clear any pending events before waiting for the key event. This can be useful to avoid processing old events that occurred before calling this function.
- Returns:
A named tuple containing the following:
key:The pressed or released key, returned as a string (e.g., “SPACE”). If max_wait is reached without any event, this will be None.
modifiers:A string representation of the modifiers (e.g., “CTRL|SHIFT”) pressed at the time of the event. If no modifiers were pressed, this will be an empty string. If modifiers are ignored (modifiers=None), this will also be empty.
timestamp:The timestamp when the key event occurred, using either the provided clock or time.time().
event:A string representing whether the key event was a “press” or “release”.
- Return type:
KeyEvent
- Raises:
AssertionError – If an invalid event type is passed or if the window is not found.
Examples
Wait for the SPACE key to be pressed or released within 5 seconds:
>>> key_event = wait_key(keys="SPACE", max_wait=5) >>> if key_event.key: ... print(f"Key {key_event.key} pressed with {key_event.modifiers}") ... else: ... print(f"No key pressed within 5 seconds, timestamp: {key_event.timestamp}")
Wait for any key press event:
>>> key_event = wait_key(max_wait=10) >>> print(f"Key {key_event.key} pressed with {key_event.modifiers} ({key_event.timestamp})")