Sunday, May 20, 2012

Python: How to load and display an image (GIF) in tkinter

Credits: mg_, Carlos, George, Bryan Oakley

This is a simple code that get the input from the inputBox to myText, and also display a picture (gif only) to the tkinter window. Depending on what else you need to check or do, you can add more functions to it. Notice you might have to play around with the order of the line image = tk.PhotoImage(data=b64_data). Because if you put it right after b64_data = .... It will gives you error. See reference at the bottom if you want to learn more.

import tkinter as tk
import urllib.request
import base64

# Download the image using urllib
URL = ""

u = urllib.request.urlopen(URL)
raw_data =

b64_data = base64.encodestring(raw_data)

# The string you want to returned is somewhere outside
myText = 'empty'

def getText():
    global myText
    # You can perform check on some condition if you want to
    # If it is okay, then store the value, and exist
    myText = inputBox.get()
    print('User Entered:', myText)

root = tk.Tk()

# Just a simple title
simpleTitle = tk.Label(root)
simpleTitle['text'] = 'Please enter your input here'

# The image (but in the label widget)
image = tk.PhotoImage(data=b64_data)
imageLabel = tk.Label(image=image)

# The entry box widget
inputBox = tk.Entry(root)

# The button widget
button = tk.Button(root, text='Submit', command=getText)


Here is the reference if you want to know more about the Tkinter Entry Widget:
Reference on how to get the image: Stackoverflow Question