我试图用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()
答案 0 :(得分:0)
如果您使用Tkinter PhotoImage,则效果很好:
photo=PhotoImage(file="pilner.png")
在win10下运行Python 3.6.5。
答案 1 :(得分:0)
您使用的png
图像具有一定的透明度。按钮的默认颜色为light grey
。如果在按下按钮后使用此行代码,则将获得预期的输出:
boton.config(bg="red")
我尝试制作一个包含以下名为smoke01.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="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")