Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Taking a screenshot with Pyglet [Fix'd]

In the pyglet docs, I found:

The following example shows how to grab a screenshot of your application window: pyglet.image.get_buffer_manager().get_color_buffer().save('screenshot.png')

However when using this, everything will stop until I click the mouse. Is there another way to get the screen contents in Pyglet, or to force it back into the event loop?

EDIT: I have found that actually there is a short delay (0.2 seconds~), but nothing else. Actually it is something to do with the F10 key that stops pyglet. >_>

I cannot close or delete since there is an open bounty.

like image 409
The Communist Duck Avatar asked Feb 13 '11 20:02

The Communist Duck


1 Answers

Okay, here is a complete working example in pyglet. It shows the text "hello world" taking a random walk around the window and dumps the screenshot (using the exact same line of code you posted) every time you press a key.

import pyglet, random

window = pyglet.window.Window()

label = pyglet.text.Label('Hello, world',
                          font_name='Times New Roman',
                          font_size=36,
                          x=window.width//2, y=window.height//2,
                          anchor_x='center', anchor_y='center')
@window.event
def on_draw():
    window.clear()
    label.draw()

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

def update(dt):
    label.x += random.randint(-10, 10)
    label.y += random.randint(-10, 10)

pyglet.clock.schedule_interval(update, 0.1)
pyglet.app.run()

Taking the screenshot doesn't halt the event loop. The event loop in pyglet is just lazy, and tries to do as little work as possible. You need to schedule a function to run repeatedly if you want things to keep happening on their own. Otherwise, it'll wait for an event that has a listener attached to happen. (Your code must be listening for the mouse event, which is why it resumes work when you click the mouse.)

Short answer, I suspect the fix you need is pyglet.clock.schedule_interval(...).

like image 118
tangentstorm Avatar answered Oct 12 '22 04:10

tangentstorm