An Image Button (Python and Tk)


You can put an image and text on a Tkinter button widget. This small code shows you how. The GIF image file you want to use for the button should be in the working directory, or you have to give it the full path. Incorporate the Python Image Library (PIL) for other image formats.

About the Author


# create a Tkinter button with an image and optional text
# note that Tkinter reads only GIF and PGM/PPM images
# for other image file types use the Python Image Library (PIL)
# replace the line photo1 = tk.PhotoImage(file="Press1.gif")
# with these three lines ...
# from PIL import Image, ImageTk
# image1 ="Press1.jpg")
# photo1 = ImageTk.PhotoImage(image1)
# tested with Python24     vegaseat     23dec2006

import Tkinter as tk

button_flag = True

def click():
    respond to the button click
    global button_flag
    # toggle button colors as a test
    if button_flag:
        button_flag = False
        button_flag = True

root = tk.Tk()

# create a frame and pack it
frame1 = tk.Frame(root)
frame1.pack(side=tk.TOP, fill=tk.X)

# pick a (small) image file you have in the working directory ...
photo1 = tk.PhotoImage(file="Press1.gif")

# create the image button, image is above (top) the optional text
button1 = tk.Button(frame1, compound=tk.TOP, width=155, height=55, image=photo1,
    text="optional text", bg='green', command=click)
button1.pack(side=tk.LEFT, padx=2, pady=2)

# save the button's image from garbage collection (needed?)
button1.image = photo1

# start the event loop
KiDo3Konvict 0 Newbie Poster

No matter what image I use, I get this error:

File "C:\Python27\lib\lib-tk\", line 3200, in __init__'image', 'create', imgtype, name,) + options)
_tkinter.TclError: couldn't recognize data in image file 
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Are you using an image with a GIF format?

neon_3 0 Newbie Poster

Hi vegaseat,

Thanks for the nice guide. Can you please show how do I create submenus as well using images? Also I need to incorporate lots of such buttons, so how do I layout the buttons inside a window?

Be a part of the DaniWeb community
