Keyt Weyner
Keyt Weyner

Reputation: 27

Image background black

So even though I tried to set the background to custom color the picture is automatically set with bg=black. Witch I am guessing is default. Can someone tell me in what moment I have to set the background, and how to do it so the picture doesn't get automatically filled with black.


window = Tk()
window.title('Random Password Generator')
window.geometry('400x250')
window.config(bg=GREEN)

#openImage
pic = Image.open('lock.png')
#resized
resized = pic.resize((100,150), resample=1)
new_pic = ImageTk.PhotoImage(resized)
#enter image
image = Label(image=new_pic)
image.config(compound='bottom', anchor='e')
image.grid(column=0, row=0, padx=10)

This is the result at the moment This is how it looks in the program (imagine the gray is a white and gray chess board)

  1. why is the picture still bg='black' even though I set it to GREEN

Upvotes: 1

Views: 735

Answers (2)

Rotem
Rotem

Reputation: 32104

According to this post, Tkinter labels do not support transparency.

As an alternative, we may create green image, and apply alpha_composite:

  • Create green image with RGBA color format:

     green_bk = Image.new(mode="RGBA", size=(100, 150), color=(0, 128, 0, 255))  
    
  • Apply alpha composition of resized image and green background:

    resized_bk = Image.alpha_composite(green_bk, resized)
    

Code sample:

import tkinter as tk
from PIL import Image, ImageTk

window = tk.Tk()
window.title('Random Password Generator')
window.geometry('400x250')
window.config(bg='GREEN')

pic = Image.open('lock.png') # openImage

resized = pic.resize((100,150), resample=1)  # resized

# Green color of Tkinter is (0, 128, 0) https://www.plus2net.com/python/tkinter-colors.php
green_bk = Image.new(mode="RGBA", size=(100, 150), color=(0, 128, 0, 255))  # Create green image with opaque background

resized_bk = Image.alpha_composite(green_bk, resized)  # Apply alpha composition of resized image and green background

new_pic = ImageTk.PhotoImage(resized_bk)  # Used resized_bk instead of resized
#enter image
image = tk.Label(image=new_pic)
image.config(compound='bottom', anchor='e')
image.grid(column=0, row=0, padx=10)

window.mainloop()

For testing I used the following lock.png image (the lock is transparent):
enter image description here

Tkinter output window:
enter image description here

Upvotes: 0

gEth0
gEth0

Reputation: 1

This image is filled with black even if its not on a black background. You should try to set a white bg or just pick an image witch is filled in white

Upvotes: -1

Related Questions