This recipe will let you embed GIF images inside of your source code for use in Tkinter buttons, labels, etc. It's really handy for making toolbars, etc. without worrying about having the right icon files installed.
The basic technique is to encode the GIF with base64 and store it as a string literal in the Python code to be passed to Tk PhotoImage.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
# this code fragment will convert a GIF to python source code import base64 print "icon='''\\\n" + base64.encodestring(open("icon.gif", "rb").read()) + "'''" # here's the result icon='''R0lGODdhFQAVAPMAAAQ2PESapISCBASCBMTCxPxmNCQiJJya/ISChGRmzPz+/PxmzDQyZDQyZDQy ZDQyZCwAAAAAFQAVAAAElJDISau9Vh2WMD0gqHHelJwnsXVloqDd2hrMm8pYYiSHYfMMRm53ULlQ HGFFx1MZCciUiVOsPmEkKNVp3UBhJ4Ohy1UxerSgJGZMMBbcBACQlVhRiHvaUsXHgywTdycLdxyB gm1vcTyIZW4MeU6NgQEBXEGRcQcIlwQIAwEHoioCAgWmCZ0Iq5+hA6wIpqislgGhthEAOw== ''' # to use this in Tkinter: import Tkinter root = Tkinter.Tk() iconImage=Tkinter.PhotoImage(master=root, data=icon) Tkinter.Button(image=iconImage).pack()
The current PhotoImage supports GIF and PPM, but inline data is only supported for GIF. You can use file='filename' instead of data=string for GIF or PPM.
You must keep a reference to the PhotoImage object yourself; it is not kept by the Tkinter widget. If you just pass it to Button and forget it you will become very frustrated!
The master argument on PhotoImage is optional; it defaults to the default application window. If you create a new application window (by calling Tk() again), then you will need to create your images in that context and you will need to supply the master argument.