Creating a Grayscale Ramp in Tkinter

January 12, 1998 | Fredrik Lundh

This script creates and displays a grayscale ramp using only standard Tkinter operations.

The put method takes a “2D tuple”, where the outer tuple contains one tuple for each row of pixels, and the inner tuples contain pixel values for each column. Pixel values are given as colour strings.

The zoom method is used to resize the image. It takes integer scale factors, so you can only use it to increase the size by a full integer multiple. The resample method does the same thing in the opposite direction. It had probably been a bit more convenient to have a single resize method, but the Tk designers didn’t think of that (if you need this, use PIL).

from Tkinter import *

# must initialize interpreter before you can create an image
root = Tk()

data = range(256) # 0..255

im = PhotoImage(width=len(data), height=1)

# tkinter wants a list of pixel lists, where each item is
# a tk colour specification (e.g. "#120432").  map the
# data to a list of strings, and convert the list to the
# appropriate tuple structure

im.put( (tuple(map(lambda v: "#%02x%02x%02x" % (v, v, v), data)),) )

# resize the image to the appropriate height

im = im.zoom(1, 32)

# and display it

w = Label(root, image=im, bd=0)



A Django site. rendered by a django application. hosted by webfaction.