gpt4 book ai didi

python - 如何在 tkinter 中创建具有 .png 背景的按钮

转载 作者:行者123 更新时间:2023-12-01 09:07:59 25 4
gpt4 key购买 nike

我尝试使用 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 图像。按钮默认颜色为浅灰色。如果您在制作按钮后使用这行代码,那么您将获得预期的输出:

boton.config(bg="red")

我尝试制作一个包含以下名为 smoke01.png 的 png 图像的按钮:

enter image description here

完整代码如下:

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()

好吧,当按钮未按下时,背景为红色,但是当按钮处于事件状态时,背景再次变为灰色。为此,您可以使用:

,而不是 boton.config(bg="red")
boton.config(bg="red",activebackground="red")

这是屏幕截图:
enter image description here

关于python - 如何在 tkinter 中创建具有 .png 背景的按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51889265/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com