【问题标题】:Some transparent images on labels have black backgrounds when using PIL使用 PIL 时,标签上的某些透明图像具有黑色背景
【发布时间】:2021-12-30 10:42:40
【问题描述】:

我有一个框架,可以在上面放置多个标签。所有这些标签都包含 png 图像,有些会填满整个背景,有些则不会;有透明的背景。我想获得 16x16 像素的图像并将它们调整为 32x32 以提高可见性。我注意到原始图像在调整大小时可以正常工作,但是当我将新图像添加到资产目录并使用它时,它的背景变成黑色。 我有一个资产文件夹,用于存储我的 png 图像。我确信他们每个人都应该有透明的背景,至少根据我的照片编辑器。

这是最少的代码:

from tkinter import *
from PIL import Image, ImageTk
import os
project_path = os.path.dirname(os.path.abspath(__file__))
root = Tk()

button_frame1 = Frame(root)
button_frame1.pack(side=TOP)
Label(button_frame1, text="Hotbar",padx=8).grid(row=0,column=2)
hotbarFrame = Frame(button_frame1, bg="white", width=288, height=32, highlightbackground="black", highlightthickness=1)
hotbarFrame.grid(row=0,column=3,padx=10)
hotbarItems = ["dirt", "grass_block_side", "grass", "stone", "cobblestone", "oak_planks", "oak_log", "oak_leaves2", "glass"]
hotbarImages, hotbarSlots = {}, []

for slot in range(len(hotbarItems)):
    item = hotbarItems[slot]
    item_file = open(project_path + "\\assets\\blocks\\" + item + ".png", "rb")
    hotbarImages[item] = ImageTk.PhotoImage(Image.open(item_file).resize((32,32), Image.NONE))
    hotbarSlots.append(Label(hotbarFrame, image=hotbarImages[item], width=32, height=32, highlightthickness=1))
    hotbarSlots[slot].grid(row=0,column=slot)

root.mainloop()

输出: Notice that the eighth icon has a black background, even though it's transparent.

Click here to see the original eighth icon.

【问题讨论】:

  • 可能是因为图片不是“RGBA”模式。尝试将其转换为“RGBA”模式:Image.open(item_file).resize((32,32), Image.NONE).convert("RGBA").
  • 适用于我的实际脚本。 (不知何故在另一个脚本上它不起作用,这很奇怪。)

标签: python tkinter python-imaging-library png python-3.9


【解决方案1】:

问题是你的PNG图片不是RGBA模式,而是P模式。

P 模式 8 位像素,使用调色板映射到任何其他模式

from PIL import Image

im = Image.open("D:/oak_leaves2.png")
print(im.mode)        # P
im.show()

以下简单脚本显示结果

from PIL import Image, ImageTk
import tkinter as tk

root = tk.Tk()

frame = tk.Frame(root, bg='blue')
frame.pack(fill='both', expand=1)

im = Image.open("D:/oak_leaves2.png").resize((80, 80), Image.BICUBIC)
image = ImageTk.PhotoImage(im)

label = tk.Label(frame, text='Hello', image=image)
label.pack()

root.mainloop()

实际上,它看起来像这样

【讨论】:

  • 这在我选择“RGBA”模式时有效。
【解决方案2】:

你应该使用这个代码

    hotbarSlots.append(Label(hotbarFrame, image=hotbarImages[item], width=32, height=32, highlightthickness=1 , bd=None))

或者可以将标签的颜色与窗口背景相同

root.config(bg="white")
hotbarSlots.append(Label(hotbarFrame, image=hotbarImages[item], width=32,height=32, highlightthickness=1 , background="white"))

    

【讨论】:

  • 选项 1(使用“bd=None”)对我不起作用,选项 2 也不起作用。它看起来与我之前发送的输出相同。
  • 所以你需要为 Frame 设置 bd=None
  • 为什么是None 而不是0
  • @NadeemAli 仍然没有做任何事情(“bd=None”甚至“bd=0”)。
  • 正如目前所写,您的答案尚不清楚。请edit 添加其他详细信息,以帮助其他人了解这如何解决所提出的问题。你可以找到更多关于如何写好答案的信息in the help center
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-28
  • 1970-01-01
  • 2016-12-29
  • 2011-12-05
  • 2013-09-26
  • 1970-01-01
相关资源
最近更新 更多