python - 如何在 tkinter 中创建具有 .png 背景的按钮
问题描述
我尝试使用 png 文件创建一个简单的按钮,但是当我尝试加载图像时,图像的背景仍然是白色。为什么?
这是我的代码:
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()
解决方案
您正在使用png
具有一定透明度的图像。按钮默认颜色 if light grey
。如果您在制作 button 后使用这行代码,那么您将获得预期的输出:
boton.config(bg="red")
我尝试制作一个包含以下名为的 png 图像的按钮smoke01.png
:
这是完整的代码:
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()
好吧,当按钮未按下时,背景是red
,但当按钮处于活动状态时,背景再次变为灰色。为此boton.config(bg="red")
,您可以使用:
boton.config(bg="red",activebackground="red")