Mystic_Force
Mystic_Force

Reputation: 263

How create button with .png background in tkinter

I try to to create a simple button with a png file but when I try to load the image, the background of the image remains white. Why?

This is my code:

from tkinter import *
from PIL import Image, ImageTk

root = Tk()
ox = root.winfo_screenwidth()/2
oy = root.winfo_screenheight()/2
root.geometry("=300x300+%d+%d" % (ox-400,oy-345) )                                                                              #sin bordes

miFrame=Frame(root,bg='red',width=800,height=700)
miFrame.pack()  

can = Canvas(root,bg='red',width=800,height=700)
can.pack()
photo=ImageTk.PhotoImage(file="menos1.png")
can.create_image(150,150,image=photo)

boton = Button(miFrame,image=photo,border=0)

boton.place(x=60,y=100)


root.mainloop()

Upvotes: 1

Views: 7035

Answers (2)

Nouman
Nouman

Reputation: 7303

You are using png image having some transparency. The button default color if light grey. If you use this line of code after making your button , then you will get the expected output:

boton.config(bg="red")

I tried making a button containing following png image named smoke01.png:

enter image description here

Here is the full code:

from tkinter import *
from PIL import Image, ImageTk

root = Tk()
ox = root.winfo_screenwidth()/2
oy = root.winfo_screenheight()/2
root.geometry("=300x300+%d+%d" % (ox-400,oy-345) )                                                                              #sin bordes

miFrame=Frame(root,bg='red',width=800,height=700)
miFrame.pack()  

can = Canvas(root,bg='red',width=800,height=700)
can.pack()
photo=ImageTk.PhotoImage(file="smoke01.png")
can.create_image(150,150,image=photo)

boton = Button(miFrame,image=photo,border=0)
boton.config(bg="red")
boton.place(x=60,y=100)


root.mainloop()

Well, when the button is not pressed the background is red but when the button is active , then the background becomes grey again. For this, rather than boton.config(bg="red") , you can use :

boton.config(bg="red",activebackground="red")

Here is a screenshot:
enter image description here

Upvotes: 1

figbeam
figbeam

Reputation: 7176

If you use Tkinter PhotoImage it works fine:

photo=PhotoImage(file="pilner.png")

running Python 3.6.5 under win10.

Upvotes: 0

Related Questions