【发布时间】: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.
【问题讨论】:
-
可能是因为图片不是“RGBA”模式。尝试将其转换为“RGBA”模式:
Image.open(item_file).resize((32,32), Image.NONE).convert("RGBA"). -
适用于我的实际脚本。 (不知何故在另一个脚本上它不起作用,这很奇怪。)
标签: python tkinter python-imaging-library png python-3.9