Ethan Miller

Unless otherwise noted, all work licensed under : Creative Commons License

Pyglet + PyCairo 'Hello World'

Feb 22 2008, 4:10PM

I've been excited about using Pyglet for all it's nice timing/windowing/event handling. And then I got excited about the nice graphics programming from PyCairo.

I couldn't find any examples of the two combined, so, with the help of this PyGame example I munged the following together. Just posting in case it helps someone else... we'll see where all this takes me...


import cairo, cStringIO
from pyglet import font, window, image
w, h = 400, 400
rot = 0.04
# pyglet
win = window.Window(width=w, height=h)
ft = font.load('Arial', 36)
text = font.Text(ft, 'Hello, World!')
# cairo
surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, w, h)
ctx = cairo.Context(surface)
ctx.translate(200, 200)

while not win.has_exit:
        # cairo
        ctx.rotate(rot)
        # clear to black
        ctx.set_source_rgb(0, 0, 0)
        ctx.paint()
        # lifted from pycairo example...
        ctx.set_line_width(15)
        ctx.set_source_rgb(255, 0, 0)
        ctx.move_to(0, -100)
        ctx.line_to(100, 100)
        ctx.rel_line_to(-200, 0)
        ctx.close_path()
        ctx.stroke()
        # output to file-like obj
        f = cStringIO.StringIO()
        surface.write_to_png(f)
        # rewind
        f.seek(0)
        # load
        pic = image.load('hint.png', file=f)
        #pyglet
        win.dispatch_events()
        win.clear()
        pic.blit(0, 0)
        text.draw()
        win.flip()

[7/28/08 edit] A discussion on the pyglet-users list comments on my code, and includes a better solution.

Tags : code pycairo pyglet python


blog comments powered by Disqus