Search code examples
pythonopenglscreenshotpyglet

Black screenshot using Pyglet


I've been trying to grab a screenshot of a window I created using the Pyglet module of Python. I used this line of code to grab the screenshot:

pyglet.image.get_buffer_manager().get_color_buffer().save('screenshot1.png')

Though there is no error occurring when I'm running the program and the screenshot file is created, the file is just black. Here is the complete code:

import pyglet
from pyglet import gl

window = pyglet.window.Window(500, 500)

@window.event
def on_draw():
    window.clear()
    pyglet.graphics.draw(2, pyglet.gl.GL_LINES, ('v2i', (200, 200, 400, 400)))


pyglet.image.get_buffer_manager().get_color_buffer().save('screenshot1.png')

pyglet.app.run()

Solution

  • You are taking a screenshot before the window had a chance to draw anything. Because the on_draw() event handler is only called after you start the the event handling loop with pyglet.app.run().

    One possible solution is to put the screenshot function into an event handler as well, for example:

    @window.event
    def on_key_press(symbol, modifiers):
        pyglet.image.get_buffer_manager().get_color_buffer().save('screenshot1.png')
    

    This way, the screenshot is only taken after you press a key, which allows the window to draw its content first.