如何在Tkinter中添加无背景PNG图片?解决白色背景问题
解决Tkinter中PNG透明背景显示白色的问题
问题出在你创建的Label默认带有窗口背景色(通常为白色),没有适配透明图片的alpha通道,导致透明区域显示Label的背景色。只需做以下修改即可解决:
- 创建显示透明PNG的Label时,指定其背景色与父窗口背景一致,同时去除边框
- 确保PIL加载图片时保留alpha通道(默认会自动保留,无需额外操作)
修改后的完整代码:
from tkinter import * from PIL import ImageTk, Image root = Tk() root.title("7 Evelyn") root.geometry('1600x900') # background image image_0 = Image.open("C:\\Users\\cerbi\\OneDrive\\Desktop\\FoodCartRes\\Background-01.png").resize((1600, 900)) bck_end = ImageTk.PhotoImage(image_0) lbl = Label(root, image=bck_end) lbl.place(y=0, x=0) # pick a stand Label(root, text="Choose a Stand", font=('Century Gothic', 30, "bold"), bg=root['bg']).place(y=80, x=600) # Stands # Fruit stand fruit_stand_image = Image.open("C:\\Users\\cerbi\\OneDrive\\Desktop\\FoodCartRes\\FruitStand\\fruitstand-01.png") fruit_stand = ImageTk.PhotoImage(fruit_stand_image.resize((400, 500))) # 关键修改:设置Label背景与窗口一致,去除边框 lbl = Label(root, image=fruit_stand, bg=root['bg'], borderwidth=0) lbl.place(y=200, x=175) root.mainloop()
额外提示:
- 若后续给窗口设置了自定义背景色,需将
root['bg']替换为对应的颜色值 - 确认你的PNG图片确实带有有效alpha通道(可通过PS、GIMP等工具查看)
内容的提问来源于stack exchange,提问作者Bart
相关产品推荐
相关产品推荐

