Embedding Inline GIFs Using Tkinter
Credit: Brent Burley
Problem
You need to embed GIF images inside your source code—for use in Tkinter buttons, labels, etc.—to make toolbars and the like without worrying about installing the right icon files.
Solution
A lively Tkinter GUI can include many small images. However, you
probably shouldn’t require that a small GIF file be
present for each of these; ensuring the presence of many small files
is a bother, and if they’re missing, your GUI may be
unusable or look wrong. Fortunately, you can construct
Tkinter
PhotoImage objects with inline data.
It’s easy to convert a GIF to inline form as Python
source code:
import base64
print "icon='''\\\n" + base64.encodestring(open("icon.gif", "rb").read( )) + "'''"You can then split the result into lines of reasonable length:
icon='''R0lGODdhFQAVAPMAAAQ2PESapISCBASCBMTCxPxmNCQiJJya/ISChGRmzPz+/PxmzDQyZ DQyZDQyZDQyZCwAAAAAFQAVAAAElJDISau9Vh2WMD0gqHHelJwnsXVloqDd2hrMm8pYYiSHYfMMRm 53ULlQHGFFx1MZCciUiVOsPmEkKNVp3UBhJ4Ohy1UxerSgJGZMMBbcBACQlVhRiHvaUsXHgywTdyc LdxyB gm1vcTyIZW4MeU6NgQEBXEGRcQcIlwQIAwEHoioCAgWmCZ0Iq5+hA6wIpqislgGhthEAOw== '''
and use it in Tkinter:
import Tkinter
root = Tkinter.Tk( )
iconImage = Tkinter.PhotoImage(master=root, data=icon)
Tkinter.Button(image=iconImage).pack( )Discussion
The basic technique is to encode the GIF with the standard Python
module base64 and store the results as a string
literal in the Python code, which will be passed to
Tkinter’s PhotoImage. The current release of ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access