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.
Python/Tkinter Imagebutton using Base64
# 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
grape_gif='''\
R0lGODlhIAAgALMAAAAAAAAAgHCAkC6LV76+vvXeswD/ANzc3DLNMubm+v/6zS9PT6Ai8P8A////
/////yH5BAEAAAkALAAAAAAgACAAAAS00MlJq7046803AF3ofAYYfh8GIEvpoUZcmtOKAO5rLMva
0rYVKqX5IEq3XDAZo1GGiOhw5rtJc09cVGo7orYwYtYo3d4+DBxJWuSCAQ30+vNTGcxnOIARj3eT
YhJDQ3woDGl7foNiKBV7aYeEkHEignKFkk4ciYaImJqbkZ+PjZUjaJOElKanqJyRrJyZgSKkokOs
NYa2q7mcirC5I5FofsK6hcHHgsSgx4a9yzXK0rrV19gRADs=
'''
root = tk.Tk()
gif_image = tk.PhotoImage(data=grape_gif)
b1 = tk.Button(root, image=gif_image)
b1.pack(pady=10)
# save the button image from garbage collection!
b1.image = gif_image
root.mainloop()
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague
Be a part of the DaniWeb community
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.