== Introduction == [[http://www.pygame.org|PyGame]] is a platform-independent wrapper for the SDL libraries. A common question on the wxPython-users mailing list is how to display [[http://www.pygame.org|PyGame]] graphics within a wxPython window. This page attempts to gather some of the common responses and code samples in a central location. == What Objects are Involved == In addition to wxPython, you'll need to install [[http://www.pygame.org|PyGame]]. You can download [[http://www.pygame.org|PyGame]] at http://www.pygame.org/download.shtml . == Play Video/Audio Using PyGame == You can also use Py``Game to play video and audio files in a wxPython window. wx``Game``Canvas is not really necessary because `pygame.movie.play()` runs in its own thread. We're still not sure though how stable this really is, and if it works on Mac or Linux. Only tested on Windows. Also the sound quality of SDL (the library used by Py``Game) might not be as good as other audio/video playing libraries, so this might not be a good option for those of you wanting to create your own MP3 players. @TODO: some of the following examples are incompatible with wxPython 3.0 due to changes in the package structure and import statements {{{ #!python class myFrame(wx.wxFrame): def play(self, filename): import sys ##Note we call the GetHandle() method of a control in the window/frame, not the wxFrame itself self.hwnd = self.GetChildren()[0].GetHandle() if sys.platform == "win32": os.environ['SDL_VIDEODRIVER'] = 'windib' os.environ['SDL_WINDOWID'] = str(self.hwnd) #must be before init ## NOTE WE DON'T IMPORT PYGAME UNTIL NOW. Don't put "import pygame" at the top of the file. import pygame pygame.display.init() self.movie = pygame.movie.Movie(filename) if self.movie.has_video(): w,h = self.movie.get_size() if w<=0 or h<=0: w,h = 1,1 else: #? need something to display if audio only. #We can't have a 0,0 canvas, pygame/SDL doesn't like that. w,h = 1,1 self.display = pygame.display.set_mode((w,h)) #size no matter self.movie.set_display(self.display) self.movie.play() }}} --Doug Holton Based on the code samples above and code by Kevin Altis. ''Other Options:'' David Woods' [[http://www2.wcer.wisc.edu/Transana/Develop|Transana]] might hold another option for playing video & audio files in a wxPython application. I think he is using Windows Media Player as a COM control or something, and something else to play video on the Mac. == Additional Resources == * [[http://aspn.activestate.com/ASPN/search?query=pygame&x=0&y=0&type=Archive_wxPython-users_list|Search the wx-python user list for PyGame]] * [[http://pygame.org/docs/index.html|PyGame documentation]] == Old Code Samples == This code was shamelessly cribbed from the wxPython-users list archive. It demonstrates a couple of key concepts. First, it defines a {{{wxSDLWindow}}} class which wraps [[http://www.pygame.org|PyGame]] in a top-level wxPython frame. This class is suitable for use in mixed wxPython/[[http://www.pygame.org|PyGame]] apps. To actually do the drawing, you subclass {{{wxSDLWindow}}} and implement the {{{draw}}} method (the {{{CircleWindow}}} class in this example). Note this code has been tested on Linux only using [[http://www.pygame.org|PyGame]] 1.5.5 and wxPython 2.4.0.2. {{{ #!python import os from wxPython.wx import * import pygame class wxSDLWindow(wxFrame): def __init__(self, parent, id, title = 'SDL window', **options): options['style'] = wxDEFAULT_FRAME_STYLE | wxTRANSPARENT_WINDOW wxFrame.__init__(*(self, parent, id, title), **options) self._initialized = 0 self._resized = 0 self._surface = None self.__needsDrawing = 1 EVT_IDLE(self, self.OnIdle) def OnIdle(self, ev): if not self._initialized or self._resized: if not self._initialized: # get the handle hwnd = self.GetHandle() os.environ['SDL_WINDOWID'] = str(hwnd) if sys.platform == 'win32': os.environ['SDL_VIDEODRIVER'] = 'windib' pygame.init() EVT_SIZE(self, self.OnSize) self._initialized = 1 else: self._resized = 0 x,y = self.GetSizeTuple() self._surface = pygame.display.set_mode((x,y)) if self.__needsDrawing: self.draw() def OnPaint(self, ev): self.__needsDrawing = 1 def OnSize(self, ev): self._resized = 1 ev.Skip() def draw(self): raise NotImplementedError('please define a .draw() method!') def getSurface(self): return self._surface if __name__ == "__main__": class CircleWindow(wxSDLWindow): "draw a circle in a wxPython / PyGame window" def draw(self): surface = self.getSurface() if surface is not None: topcolor = 5 bottomcolor = 100 pygame.draw.circle(surface, (250,0,0), (100,100), 50) pygame.display.flip() def pygametest(): app = wxPySimpleApp() sizeT = (640,480) w = CircleWindow(None, -1, size = sizeT) w.Show(1) app.MainLoop() pygametest() }}} === On Windows, however... === As has been indicated on the mailing list and so forth, a resource that I did not properly peruse during my quest for getting this thing working on Windows, the above does not work on Windows. This page confounded me because it absolutely in no way works. Well, ok, it works a bit, but not really acceptably. Riccardo Trocca however has worked out and posted the solution, so I'll copy it here from its home in the archives at http://aspn.activestate.com/ASPN/Mail/Message/1627085 . His statement is that merely importing pygame does some initialization which makes the setting of environment variables useless. Here's the code that does what we Windows users want. Note: this code only tested to work in Python 2.4 with wx2.6 and Pygame 1.7.1. It is known not work with pygame 1.6.x. This used to be for older versions of wx, but it was updated in July 2006. Note: '''stefano''' is right ; I found upgrading to SDL 1.2.8 fixed the crashes. And you won't receive mouse events (from SDL) with this technique. Also, the SDL_WINDOWID value used below will effectively only be read on the first import of pygame, so you can only make one window per Python process. -markh (''SDL only allows one active window anyway (at least, according to the docs), so this isn't actually a problem.'' --TomPlunket) (''the below code only allows one window to be created per process even if the first window is destroyed. however there is a way to create more than one window per process but they can not exist at the same time. see the section I added farther down.'' -BenjaminPowers) '''IMPORTANT NOTE:''' Pygame has issues running in anything besides the main thread. The below code will likely be unstable. I'm leaving this note here until I can fix the example myself, but a solution more like the above should be used where any pygame event handling and drawing should happen in an '''OnIdle''' handler or using a '''wx.Timer'''. I had issues with code based on the below while also using twisted, and they went away when I ran pygame code from a twisted LoopingCall (which runs the code in the main thread). --ClaudiuSaftoiu {{{ #!python import wx import os import thread global pygame # when we import it, let's keep its proper name! class SDLThread: def __init__(self,screen): self.m_bKeepGoing = self.m_bRunning = False self.screen = screen self.color = (255,0,0) self.rect = (10,10,100,100) def Start(self): self.m_bKeepGoing = self.m_bRunning = True thread.start_new_thread(self.Run, ()) def Stop(self): self.m_bKeepGoing = False def IsRunning(self): return self.m_bRunning def Run(self): while self.m_bKeepGoing: e = pygame.event.poll() if e.type == pygame.MOUSEBUTTONDOWN: self.color = (255,0,128) self.rect = (e.pos[0], e.pos[1], 100, 100) print e.pos self.screen.fill((0,0,0)) self.screen.fill(self.color,self.rect) pygame.display.flip() self.m_bRunning = False; class SDLPanel(wx.Panel): def __init__(self,parent,ID,tplSize): global pygame wx.Panel.__init__(self, parent, ID, size=tplSize) self.Fit() os.environ['SDL_WINDOWID'] = str(self.GetHandle()) os.environ['SDL_VIDEODRIVER'] = 'windib' import pygame # this has to happen after setting the environment variables. pygame.display.init() window = pygame.display.set_mode(tplSize) self.thread = SDLThread(window) self.thread.Start() def __del__(self): self.thread.Stop() class MyFrame(wx.Frame): def __init__(self, parent, ID, strTitle, tplSize): wx.Frame.__init__(self, parent, ID, strTitle, size=tplSize) self.pnlSDL = SDLPanel(self, -1, tplSize) #self.Fit() app = wx.PySimpleApp() frame = MyFrame(None, wx.ID_ANY, "SDL Frame", (640,480)) frame.Show() app.MainLoop() }}} Thanks, Riccardo! -tom! === Creating new pygame windows after an old pygame window has been destroyed === Only one pygame surface can exists at one time in the same python process. However, a new surface can be created provided the previous surface has been properly destroyed. The above sample do not show this as such I crested my own re-useing most of the above code and pulling from one of the wx examples. reed the comments to find the relevant changes. {{{ #!python import wx import wx.aui import os import threading global pygame # when we import it, let's keep its proper name! global pygame_init_flag pygame_init_flag = False from pygame.locals import * import sys; sys.path.insert(0, "..") class ParentFrame(wx.aui.AuiMDIParentFrame): def __init__(self, parent): wx.aui.AuiMDIParentFrame.__init__(self, parent, -1, title="AuiMDIParentFrame", size=(640,480), style=wx.DEFAULT_FRAME_STYLE) self.count = 0 mb = self.MakeMenuBar() self.SetMenuBar(mb) self.CreateStatusBar() def MakeMenuBar(self): mb = wx.MenuBar() menu = wx.Menu() item = menu.Append(-1, "New SDL child window\tCtrl-N") self.Bind(wx.EVT_MENU, self.OnNewChild, item) item = menu.Append(-1, "Close parent") self.Bind(wx.EVT_MENU, self.OnDoClose, item) mb.Append(menu, "&File") return mb def OnNewChild(self, evt): self.count += 1 child = ChildFrameSDL(self, self.count) child.Show() def OnDoClose(self, evt): self.Close() class ChildFrameSDL(wx.aui.AuiMDIChildFrame): def __init__(self, parent, count): wx.aui.AuiMDIChildFrame.__init__(self, parent, -1, title="Child: %d" % count) mb = parent.MakeMenuBar() menu = wx.Menu() item = menu.Append(-1, "This is child %d's menu" % count) mb.Append(menu, "&Child") self.SetMenuBar(mb) p = SDLPanel(self, -1, (640,480)) sizer = wx.BoxSizer() sizer.Add(p, 1, wx.EXPAND) self.SetSizer(sizer) wx.CallAfter(self.Layout) class SDLThread: def __init__(self,screen): self.m_bKeepGoing = self.m_bRunning = False self.screen = screen self.color = (255,0,0) self.rect = (10,10,100,100) self.thread = None self.init = True def Start(self): #I rewrote this to use the higherlevel threading module self.m_bKeepGoing = self.m_bRunning = True self.thread = threading.Thread(group=None, target=self.Run, name=None, args=(), kwargs={}) self.thread.start() def Stop(self): self.m_bKeepGoing = False #this important line make sure that the draw thread exits before #pygame.quit() is called so there is no errors self.thread.join() def IsRunning(self): return self.m_bRunning def Run(self): while self.m_bKeepGoing: #I rewrote this to only draw when the position changes e = pygame.event.poll() if e.type == pygame.MOUSEBUTTONDOWN: self.color = (255,0,128) self.rect = (e.pos[0], e.pos[1], 100, 100) print e.pos self.screen.fill((0,0,0)) self.screen.fill(self.color,self.rect) if self.init: self.screen.fill((0,0,0)) self.screen.fill(self.color,self.rect) pygame.display.flip() self.m_bRunning = False; print "pygame draw loop exited" class SDLPanel(wx.Panel): def __init__(self,parent,ID,tplSize): global pygame global pygame_init_flag wx.Panel.__init__(self, parent, ID, size=tplSize) self.Fit() os.environ['SDL_WINDOWID'] = str(self.GetHandle()) os.environ['SDL_VIDEODRIVER'] = 'windib' #here is where things change if pygame has already been initialized #we need to do so again if pygame_init_flag: #call pygame.init() on subsaquent windows pygame.init() else: #import if this is the first time import pygame pygame_init_flag = True #make sure we know that pygame has been imported pygame.display.init() window = pygame.display.set_mode(tplSize) self.thread = SDLThread(window) self.thread.Start() def __del__(self): self.thread.Stop() print "thread stoped" #very important line, this makes sure that pygame exits before we #reinitialize it other wise we get errors pygame.quit() app = wx.PySimpleApp() frame = ParentFrame(None) frame.Show() app.MainLoop() }}} you will notice that two SDL panels created at the same time causes python to crash, but if you close the first one before creating a second you can. -BenjaminPowers