Quick answer: Call pygame.scrap.init() after pygame.display.set_mode(). On Linux, also set the mode to SCRAP_CLIPBOARD to access Ctrl-C content.
A simple text editor in pygame tries to read the clipboard for paste. pygame.scrap.get() raises a pygame.error: scrap module not initialized. Calling init() before display.set_mode also raises.
Correct Init Order
pygame.init()
screen = pygame.display.set_mode((800, 600))
pygame.scrap.init()
pygame.scrap.set_mode(pygame.SCRAP_CLIPBOARD)
display.set_mode creates the window. scrap.init binds to its clipboard channel.
Read and Write
# write
pygame.scrap.put(pygame.SCRAP_TEXT, b'Hello!')
# read
data = pygame.scrap.get(pygame.SCRAP_TEXT)
if data:
text = data.decode('utf-8').rstrip('\x00')
Scrap deals in bytes. Encode/decode to/from str. Note the null-terminator trim — Windows clipboard text often has trailing nulls.
Linux: PRIMARY vs CLIPBOARD
Linux X11 has two selections:
- SCRAP_SELECTION: highlight-to-copy (mouse select).
- SCRAP_CLIPBOARD: Ctrl-C explicit copy.
Default mode is SELECTION on some Linux setups. For typical paste support set CLIPBOARD.
Wayland Note
On Wayland, scrap requires SDL2’s Wayland backend with clipboard support. Recent pygame-ce (community edition) handles this; older pygame might fall back to X11/XWayland.
Verifying
Copy text in your OS, then in the game read scrap.get(SCRAP_TEXT) — matches. Set scrap, paste in another app — matches. Test across platforms; behavior is similar with the noted Linux SELECTION/CLIPBOARD distinction.
“Init after display, set CLIPBOARD mode, decode bytes. Three lines that make clipboard support reliable.”
For paste-into-text-field UX, also support Cmd+V on macOS by handling KMOD_META in key event filter alongside Ctrl.