faqts : Computers : Programming : Languages : Python : Snippets

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

3 of 4 people (75%) answered Yes
Recently 2 of 3 people (67%) answered Yes

Entry

Writing pixels / creating greyscale ramp

Jul 5th, 2000 10:02
Nathan Wallace, Hans Nowak, Snippet 283, Fredrik Lundh


"""
Packages: gui.tkinter
"""
"""
> Ok, I've managed to create an image, using xx=PhotoImage(file), and I
> can retrieve pixel values from that image using xx.get(x,y).
> 
> Now I want to use the put() method to write a pixel.
> 
> How do I do that?  I would have expected that put() would take a string
> of pixel values for the data argument, but that doesn't seem to be the
> case. ...
from the eff-bot archives:
"""
#
# create a greyscale ramp using pure Tkinter
#
# fredrik lundh, january 1998
#
# fredrik@pythonware.com
# http://www.pythonware.com
#
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)
w.pack()
mainloop()
# after playing with this a little, you'll love
# the Python Imaging Library.