Python/Tkinter Imagebutton using Base64

Ene Uran 0 Tallied Votes 2K Views Share

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

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

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

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.