FAQ Index - Search - Recent Changes - Everything - Add entry

<< Previous Entry | FAQ Entry 23.42 | Next Entry >>

23.42. How can integrate PyGTK with SDL / pygame ?

There are a couple of ways to do the integration;

* Inprocess

This method makes it possible to use pygame / SDL in the same process as your PyGTK application, eg you use PyGTK to construct the menus, buttons and windows, but pygame to draw parts of the interface.

* Out of process

This is more like a frontend to an already existing application, you decouple both of the applications (the gtk frontend and the pygame application).

This example will demonstrate the inprocess option, which is more attractive since it's easier to integrate the two frameworks together.

 import os

 import gobject
 import gtk
 import pygame

 WINX = 400
 WINY = 200

 window = gtk.Window()
 window.connect('delete-event', gtk.main_quit)
 window.set_resizable(False)
 area = gtk.DrawingArea()
 area.set_app_paintable(True)
 area.set_size_request(WINX, WINY)
 window.add(area)
 area.realize()

 # Force SDL to write on our drawing area
 os.putenv('SDL_WINDOWID', str(area.window.xid))

 # We need to flush the XLib event loop otherwise we can't
 # access the XWindow which set_mode() requires
 gtk.gdk.flush()

 pygame.init()
 pygame.display.set_mode((WINX, WINY), 0, 0)
 screen = pygame.display.get_surface()

 image_surface = pygame.image.load('foo.png')
 screen.blit(image_surface, (0, 0))

 gobject.idle_add(pygame.display.update)

 window.show_all()

 gtk.main()
There are two important things you have to notice; SDL_WINDOWID points to the Xwindow ID of the window you want to paint on, you need to create the window before drawing/accessing it, that's done with realize() and gtk.gdk.flush() The other is that you need to call pygame.display.update() at least once after the whole interface is constructed, we do this using gobject.idle_add in the example for simplicity, in a full blown application you need to process the SDL events and make sure that they interact with the gtk mainloop.

PyGTK FAQ Wizard | PyGTK Homepage | Feedback to faq at pygtk.org