wxPython GIFAnimationCtrl: embed animation gif in the source code

In some cases it is useful to store media files inside the python code itself. For images, PyEmbeddedImage and the script img2py.py work well. But for GIFAnimationCtrl no obvious solution is available, therefore I had to investigate the source code of wx.animate to find one.

After the solution is found, it is easy. Wx-animation consist of two parts: one part is the control to display animation, and another part is the data. The existance of the second part is not obvious, but as soon as one notices it, the rest is easy. Pseudocode:

a = wx.animate.GIFAnimationCtrl(self, -1, '') # The control

a2 = wx.animate.Animation() # The data
data = base64.b64decode(gif_img_base64)
a2.Load(cStringIO.StringIO(data))
a.SetAnimation(a2) # Bind the data and the control

a.GetPlayer().UseBackgroundColour(True)
a.Play()

The variable gif_img_base64 is base64-encoded content of a GIF file with animation. A helper program to create the code:

import sys, base64
data = sys.stdin.read()
s = base64.b64encode(data)
print 'gif_img_base64 = ('
while s:
  print '  "' + s[:62] + '"'
  s = s[62:]
print '  )'

Categories: python

Updated: