Do these 3 things before closing this tab:
1Clear out junk files and repair common Windows errors2Fix the driver behind crashes, sound loss and screen glitches3Repair Windows errors before they cause bigger problemsUse the XDG Desktop Portal when your Python program must work across Wayland desktops or inside a sandbox. It asks the compositor for permission and can present a chooser for a screen, window, or region. On a wlroots compositor such as Sway or Hyprland, grim is a smaller, scriptable option; add slurp when the user should draw a region. Libraries such as pyscreenshot can select these backends, but they cannot overcome compositor or portal limitations.
Wayland deliberately prevents an arbitrary X11-style screen grab. A blank image from Pillow or ImageGrab usually means the program bypassed the compositor-approved capture path, not that PNG writing failed.
Choose the capture path first
| Approach | Best fit | User interaction | Targets | Dependencies |
|---|---|---|---|---|
| XDG Desktop Portal | Desktop-neutral applications, Flatpak or other sandboxed programs | The desktop may show permission and selection UI | Whole screen, selected window, area, or active window, as supported by the desktop | A working xdg-desktop-portal backend and D-Bus |
| grim | wlroots compositors and unattended scripts | None for a full-screen shot; slurp provides interactive selection |
Full output or a geometry supplied with -g |
grim; slurp for region selection; compositor support for wlr-screencopy-unstable-v1 |
| pyscreenshot | Code that prefers one Python API and can tolerate backend selection | Depends on the selected backend | Depends on the backend and desktop | Python package plus a usable portal, GNOME Shell screenshot, or grim setup |
| Low-level Wayland bindings | Protocol experimentation or a compositor-specific integration | You must implement the capture flow | Only what the protocols and compositor expose | python-wayland or pywayland, protocol/version knowledge, and compositor support |
For a portable application, start with the portal. For a personal Sway or Hyprland script, start with grim. Do not treat Xwayland as a general-purpose replacement for compositor-authorized capture.
Verify the Wayland environment and install runtime pieces
Check the session type from the same graphical session that will run Python:
#1 Best Overall
- CRISP CLARITY: This 23.8″ Philips V line monitor delivers crisp Full HD 1920x1080 visuals. Enjoy movies, shows and videos with remarkable detail
- INCREDIBLE CONTRAST: The VA panel produces brighter whites and deeper blacks. You get true-to-life images and more gradients with 16.7 million colors
- THE PERFECT VIEW: The 178/178 degree extra wide viewing angle prevents the shifting of colors when viewed from an offset angle, so you always get consistent colors
- WORK SEAMLESSLY: This sleek monitor is virtually bezel-free on three sides, so the screen looks even bigger for the viewer. This minimalistic design also allows for seamless multi-monitor setups that enhance your workflow and boost productivity
- A BETTER READING EXPERIENCE: For busy office workers, EasyRead mode provides a more paper-like experience for when viewing lengthy documents
printf 'session=%sn' "$XDG_SESSION_TYPE
test -n "$WAYLAND_DISPLAY" && echo "Wayland display: $WAYLAND_DISPLAY"
XDG_SESSION_TYPE=wayland and a non-empty WAYLAND_DISPLAY are useful diagnostics, but they do not prove that a particular compositor implements every capture protocol or that a portal backend is installed.
Portal requirements
- Install and run
xdg-desktop-portaltogether with a backend for your desktop environment. - Run the program in a session with access to the user D-Bus.
- Install the Python D-Bus client used by the example:
python -m pip install dbus-next.
grim requirements
- Install
grim; installslurpas well for an interactive rectangle. - Use a compositor that supports the wlroots screencopy protocol (
wlr-screencopy-unstable-v1). - Create the destination directory yourself; neither command should be assumed to do so.
Capture through the XDG Desktop Portal in Python
The portal is the safest default for a desktop-neutral or sandboxed application. Its screenshot interface is specifically intended to let sandboxed applications request a screenshot. The compositor mediates the request, so the user may approve it, choose a window or area, or cancel it.
The following complete example uses dbus-next. It requests an interactive capture, waits for the portal’s response signal, then copies the returned URI to a predictable PNG path. A non-zero response is treated as cancellation or failure instead of being reported as success.
#!/usr/bin/env python3
import asyncio
import shutil
import uuid
from pathlib import Path
from urllib.request import urlopen
from dbus_next import Variant
from dbus_next.aio import MessageBus
BUS_NAME = "org.freedesktop.portal.Desktop"
PORTAL_PATH = "/org/freedesktop/portal/desktop"
SCREENSHOT_IFACE = "org.freedesktop.portal.Screenshot"
REQUEST_IFACE = "org.freedesktop.portal.Request"
async def capture(output: Path) -> None:
output.parent.mkdir(parents=True, exist_ok=True)
bus = await MessageBus().connect()
portal_intro = await bus.introspect(BUS_NAME, PORTAL_PATH)
portal_obj = bus.get_proxy_object(BUS_NAME, PORTAL_PATH, portal_intro)
screenshot = portal_obj.get_interface(SCREENSHOT_IFACE)
# The token identifies this request; the portal returns a request object path.
token = "python" + uuid.uuid4().hex
request_path = await screenshot.call_screenshot({
"handle_token": Variant("s", token),
"interactive": Variant("b", True),
})
request_intro = await bus.introspect(BUS_NAME, request_path)
request_obj = bus.get_proxy_object(BUS_NAME, request_path, request_intro)
request = request_obj.get_interface(REQUEST_IFACE)
finished = asyncio.get_running_loop().create_future()
def on_response(response, results):
if not finished.done():
finished.set_result((response, results))
request.on_response(on_response)
response_code, results = await finished
bus.disconnect()
if response_code != 0:
raise RuntimeError(f"Portal request was cancelled or failed (response {response_code})")
uri_variant = results.get("uri")
if uri_variant is None:
raise RuntimeError("Portal returned success without an image URI")
with urlopen(uri_variant.value, timeout=30) as source, output.open("wb") as dest:
shutil.copyfileobj(source, dest)
print(output)
if __name__ == "__main__":
try:
asyncio.run(capture(Path.home() / "Pictures" / "wayland-portal.png"))
except Exception as exc:
raise SystemExit(f"Screenshot failed: {exc}")
Run it from the graphical login, not a detached service with no D-Bus session:
PC Slower Than It Used to Be?
A free scan shows the junk files, broken settings and background clutter dragging Windows down - then fixes them in one click.Free scan · Windows 10 & 11Crashes, No Sound, or Screen Glitches?
Random freezes, missing sound and display glitches usually trace back to one bad driver. Find and replace yours safely.Free scan · under a minutepython capture_portal.py
With interactive enabled, the desktop decides how the chooser looks and which targets it offers. A portal can expose whole-screen, window, area, or active-window concepts, but support is desktop-dependent. If the user presses Cancel, preserve that distinction in your UI; silently trying an X11-only grabber can produce a misleading blank image.
Rank #2
- CRISP CLARITY: This 22 inch class (21.5″ viewable) Philips V line monitor delivers crisp Full HD 1920x1080 visuals. Enjoy movies, shows and videos with remarkable detail
- 100HZ FAST REFRESH RATE: 100Hz brings your favorite movies and video games to life. Stream, binge, and play effortlessly
- SMOOTH ACTION WITH ADAPTIVE-SYNC: Adaptive-Sync technology ensures fluid action sequences and rapid response time. Every frame will be rendered smoothly with crystal clarity and without stutter
- INCREDIBLE CONTRAST: The VA panel produces brighter whites and deeper blacks. You get true-to-life images and more gradients with 16.7 million colors
- THE PERFECT VIEW: The 178/178 degree extra wide viewing angle prevents the shifting of colors when viewed from an offset angle, so you always get consistent colors
Making portal captures production-safe
- Check that the returned URI exists and that the output file is non-empty before announcing success.
- Keep a user-visible cancellation path. Permission denial is not an exceptional “try harder” condition.
- Do not assume a portal backend offers every target on every compositor.
- For a sandbox, declare and test D-Bus access according to the packaging system you use; the Python code alone cannot grant that access.
Capture with grim, with optional slurp selection
On a compatible wlroots compositor, grim writes the compositor-provided pixels directly. This is concise and easy to automate, but it is not a universal Wayland API.
Interactive region in Python
import shutil
import subprocess
from pathlib import Path
out = Path.home() / "Pictures" / "wayland-region.png"
out.parent.mkdir(parents=True, exist_ok=True)
for program in ("slurp", "grim"):
if shutil.which(program) is None:
raise RuntimeError(f"{program} is not installed or not on PATH")
selection = subprocess.run(
["slurp"], check=False, text=True, capture_output=True
)
if selection.returncode != 0:
if selection.returncode == 1:
raise RuntimeError("Region selection was cancelled")
raise RuntimeError(selection.stderr.strip() or "slurp failed")
geometry = selection.stdout.strip()
if not geometry:
raise RuntimeError("slurp returned no geometry")
shot = subprocess.run(
["grim", "-g", geometry, str(out)],
check=False, text=True, capture_output=True
)
if shot.returncode != 0:
raise RuntimeError(shot.stderr.strip() or "grim failed")
if not out.is_file() or out.stat().st_size == 0:
raise RuntimeError("grim reported success but produced no image")
print(out)
Full-screen capture
For a full output, omit slurp and the geometry option:
from pathlib import Path
import shutil
import subprocess
out = Path.home() / "Pictures" / "wayland-full.png"
out.parent.mkdir(parents=True, exist_ok=True)
if shutil.which("grim") is None:
raise RuntimeError("grim is not installed")
subprocess.run(["grim", str(out)], check=True)
print(out)
If grim exits with a protocol or backend error, the compositor probably does not provide the required screencopy interface. Switch to the portal rather than installing an X11 grabber and hoping it works.
The Tool Desk
Outbyte PC Repair FREEClear out junk files and repair common Windows errorsFree Scan →Outbyte Driver Updater FREEFix the driver behind crashes, sound loss and screen glitchesFind Drivers →Use pyscreenshot when a library abstraction is preferable
pyscreenshot can select Wayland-capable backends such as XDG Desktop Portal through D-Bus, GNOME Shell Screenshot, or grim. That makes application code short, but backend discovery still depends on the desktop.
import pyscreenshot as ImageGrab
from pathlib import Path
out = Path.home() / "Pictures" / "pyscreenshot.png"
out.parent.mkdir(parents=True, exist_ok=True)
image = ImageGrab.grab()
image.save(out, format="PNG")
print(out)
Use this when you value one API more than exact backend control. If it returns a blank image, inspect which backend was selected and test the portal or grim example directly. A bounding box may be accepted by the library, but coordinate interpretation and region support remain backend-specific.
Rank #3
- Clear visuals. Fluid motion: A 144Hz refresh rate and 1ms MPRT deliver smooth, tear‑free motion across work, gaming, and streaming for clearer, more fluid viewing.
- Eye comfort: TÜV Rheinland 3‑star* certification reduces harmful blue light while preserving stunning color quality without compromise. *TÜV Rheinland 3-star eye comfort certification.
- Wide viewing angle: Get consistent views across a wide 178° /178° viewing angle.
- In-Plane Switching (IPS): See excellent color accuracy and consistency across wide viewing angles with In-plane Switching (IPS) technology.
- Ultra-thin bezels: Maximize your viewing experience with thin bezels.
Why Pillow and ImageGrab often return blank images
- X11 assumptions: many traditional grabbers read an X11 root window. Wayland does not expose the entire desktop that way.
- Xwayland scope: Xwayland can make an X11 application work, but it does not grant that application unrestricted access to other Wayland surfaces.
- Missing portal backend: the D-Bus service may exist without a desktop-specific implementation capable of handling screenshots.
- Unsupported compositor protocol: grim requires the wlroots screencopy interface; a Wayland session alone is not enough.
- Cancelled request treated as success: portal APIs report a response code. Always check it before reading the URI.
- Headless or remote session: a process launched by SSH, cron, or a system service may lack
WAYLAND_DISPLAY,DBUS_SESSION_BUS_ADDRESS, or an active graphical seat.
Performance, reliability, and security considerations
Latency
grim has little orchestration overhead once the compositor accepts the request. Portal captures add a D-Bus round trip and, for interactive requests, human selection time. pyscreenshot adds convenience rather than a new capture mechanism, so its speed depends on the backend it chooses.
Repeated captures
For a monitoring tool, avoid opening a new process and portal dialog for every frame. Use a compositor-appropriate capture design, document its permissions, and rate-limit output writes. The portal is designed for authorized requests, not an invisible unrestricted desktop recorder.
Data handling
Screenshots can contain passwords, notifications, and personal data. Choose an explicit destination, set restrictive file permissions where appropriate, and avoid logging returned URIs or image contents. A portal prompt is a useful user-consent boundary; do not defeat it with a silent fallback.
Or skip the browser setup
If your real goal is a screenshot of a public web page rather than the local Wayland desktop, ScreenshotNeo is a hosted alternative. It accepts a URL and returns PNG, JPEG, WebP, or PDF; it does not require you to configure a local browser or compositor.
Before capture, ScreenshotNeo accepts cookie/consent banners and removes more than 60 known consent platforms, newsletter popups, and chat widgets. Bot checks or CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed, and response headers identify the page verdict and whether the request was billed. Its MCP server provides take_screenshot, get_page_info, and capture_pdf tools for Claude, Cursor, and other MCP clients.
Every plan includes the feature set: full-page shots with lazy images loaded, CSS-selector element capture, dark mode, 12 device presets or a custom viewport, retina scale, PDF paper size/margins/landscape/page ranges, custom CSS and JavaScript, pre-capture clicks, selector hiding, selector/delay/network-idle waits, request and resource blocking, headers/cookies/user-agent/Authorization, timezone and geolocation, transparent backgrounds, resizing, configurable-TTL caching, signed image links, asynchronous jobs with signed webhooks, bulk capture of up to 100 URLs per call, a usage API, and an OpenAPI specification. Common screenshot-API parameter names are accepted to ease migration.
Rank #4
- CURVED FOR ENHANCED ENGAGEMENT: An immersive viewing experience with a curved monitor that wraps more closely around your field of vision; It creates a wider view, enhancing depth perception and minimizing peripheral distraction
- SMOOTH PERFORMANCE FOR SEAMLESS CONTENT: Stay in the action when playing games, watching videos, or working on creative projects; The 100Hz refresh rate reduces lag and motion blur so you don't miss a thing in fast-paced moments¹
- MORE GAMING POWER: Gain the edge with optimizable game settings; Color and image contrast can be adjusted to see scenes more vividly and spot enemies hiding in the dark; Game Mode adjusts any game to fill the screen so you can view every detail²
- KEEP IT EASY ON THE EYES: Care for your eyes and stay comfortable, even during long sessions; Advanced eye comfort technology certified by TÜV reduces eye strain by minimizing blue light and reducing irritating screen flicker²
- INCREASED VERSATILITY: Connect to more; Plug devices straight into your monitor for increased flexibility, making your computing environment even more convenient
Use the API documentation at https://screenshotneo.com/docs/ for authentication and optional parameters.
cURL
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
Python
import requests
r = requests.get("https://api.screenshotneo.com/v1/shot", params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"}, timeout=90)
r.raise_for_status()
open("shot.webp", "wb").write(r.content)
Node.js
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);
if (!res.ok) throw new Error(`HTTP ${res.status}`);
require('node:fs').writeFileSync('shot.webp', Buffer.from(await res.arrayBuffer()));
The Free plan includes 1,000 screenshots per month with no card. Paid plans start at $5 for 3,000 shots; yearly billing provides two months free. Create a free ScreenshotNeo account to try it.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Troubleshooting checklist
“No such file or directory” or missing executable
Install the named runtime component and verify shutil.which("grim") or shutil.which("slurp") from the same environment that runs Python. Virtual environments do not install system binaries.
Portal call cannot connect to D-Bus
Run from the logged-in graphical session and inspect DBUS_SESSION_BUS_ADDRESS. A container or sandbox also needs permission to reach the session bus and a portal backend.
Recommended Free Tools
The chooser appears, then the request returns non-zero
Treat this as denial or cancellation. Ask the user to retry, and verify that the desktop’s portal backend is running. Do not silently switch to an X11-only API.
Best Value
- 【INTEGRATED SPEAKERS】Whether you're at work or in the midst of an intense gaming session, our built-in speakers provide rich and seamless audio, all while keeping your desk clutter-free.
- 【EASY ON THE EYES】 Protect your eyes and enhance your comfort with Blue-Light Shift technology. This feature reduces harmful blue light emissions from your screen, helping to alleviate eye strain during long hours of use and promoting healthier viewing habits.
- 【WIDEN YOUR PERSPECTIVE】Our sleek minimal bezel design ensures undivided attention. The nearly bezel-free display seamlessly connects in a dual monitor arrangement, delivering an unobstructed view that lets you focus on more at once, completely distraction-free.
grim says the protocol is unavailable
Your compositor may not implement wlr-screencopy-unstable-v1. Use the portal if your desktop supplies one, or document the compositor requirement instead of claiming Wayland-wide support.
The file exists but is empty or stale
Write to a new explicit path, check the subprocess return code, and verify file size after completion. For portal captures, fetch the returned URI only after response code zero.
Works interactively but not from cron or a service
The background process probably lacks the graphical environment, D-Bus session, or user authorization. Run a user-session service with the required environment, or move capture into the foreground application that owns the session.
Quick wins for a faster PC:
Repair Windows errors before they cause bigger problemsFix Now →Scan for outdated or missing drivers - takes under a minuteDriver Scan →Frequently Asked Questions
Can a Python program capture a different Wayland user’s desktop?
Not through these normal application paths. Capture is mediated by the compositor and the user’s portal/session permissions; a process without that graphical session should fail or have no authorized target.
Does enabling Xwayland make Pillow’s screenshot function reliable?
No. Xwayland compatibility helps X11 applications draw, but it does not provide unrestricted access to other Wayland surfaces.
Which approach should a Flatpak application ship first?
Use the XDG Desktop Portal and handle its permission, selection, cancellation, and backend-availability outcomes explicitly.
Quick Recap
Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.
Free tools Windows power users keep installed
One-click scans. No signup required.

