Start New Discussion within our Software Development Community

The small images you put on buttons and such are nice, but a real pain if you have to attach all those image files to your program. Python's base64 encoding module makes it easy to convert the binary image code to a string that you can simply make part of your program. Here is an example how to do this using the Tknter GUI toolkit.

# use a base64 encoded string of a gif image in Tkinter
# (base64 converts binary data into string characters)
# good for small images, avoids having to send the image file
# the image string is created with the following simple
# Python code and is then copied and pasted to this program
# (tk only uses gif, not all gif formats work properly!)

import base64
gif_file = "grape.gif"
print "grape_gif='''\\\n" + base64.encodestring(open(gif_file).read()) + "'''"

# tested with Python25     EU      2/20/2007

import Tkinter as tk


root = tk.Tk()

gif_image = tk.PhotoImage(data=grape_gif)

b1 = tk.Button(root, image=gif_image)
# save the button image from garbage collection!
b1.image = gif_image


Ene, just a note ...
should be ...
that's why you have problems with a fair number of image files.

The article starter has earned a lot of community kudos, and such articles offer a bounty for quality replies.