Python PIL Tkinter image transparency.

Beat_Slayer 0 Tallied Votes 1K Views Share

Simple script for image transparency.

Someone asked one some time ago, and i had other but for a different system, and decided to write a Python/PIL version.

The value of the color used as transparent is the value of the pixel at position (0, 0).

You can adjust tolerance value.

Happy coding!

import Tkinter 
import Image
import ImageTk

def color_cmp(orig, comp):
    tolerance = 5   #  You can adjust color tolerance value
    inside = []
    for i in range(len(orig) - 1):
        if (orig[i] - tolerance) <= comp[i] >= (orig[i] + tolerance):
    if not inside.count(False):
        return 255
        return 0

def automask(img):
    backcolor = img.getpixel((0, 0))
    alpha_mask ='1', img.size)
    for y in range(img.size[1]):
        for x in range(img.size[0]):
            pix_color = img.getpixel((x, y))
            if color_cmp(pix_color, backcolor):
                alpha_mask.putpixel((x, y), 1)
                alpha_mask.putpixel((x, y), 0)
    return img

root = Tkinter.Tk()

masked = automask('grim_reaper.jpg'))

maskedtk = ImageTk.PhotoImage(masked)

Tkinter.Label(root, image=maskedtk).pack()

gleam.uahmed 3 Newbie Poster

Hi , But it doesnt work perfect when i want to putt that image over a button having image ! , it doesnt show any transparency

richieking 44 Master Poster

Simple transparent overlaying image

import Image

handle ="fd.png")## Your first image file name

dd"i.jpg") ## Put your second image file name here

This is more simple :)

gleam.uahmed 3 Newbie Poster

Offcourse it is but it will create a new picture and still the transperency issue remain when u putt a label with transparent pic over the button it will not work ..

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.