【问题标题】:Transparency in Tkinter Python (PNG) [duplicate]Tkinter Python(PNG)中的透明度[重复]
【发布时间】:2021-07-24 16:48:05
【问题描述】:

在我的 python 程序中,我有一个标题图像,但是它的 png 背景显示为白色。

我的图片代码如下:

from tkinter import *
from typing import final
import requests
from PIL import ImageTk, Image

root = Tk()

# get system display settings
screen_width = root.winfo_screenwidth()
screen_height = root.winfo_screenheight()

path = 'C:/Users/Sam/Desktop/Clash Clan Manager/Graphics Based Program/Game Graphics/'

root.title("Clash Clan Manager")
root.iconbitmap(path + 'CCM logo circle.ico')
root.geometry(str(screen_width) + 'x' + str(screen_height-70))

# display title
titleImage= ImageTk.PhotoImage(Image.open(path + 'clash clan manager text.png'))
titleCanvas= Canvas(root, width= 1374, height= 396)
titleCanvas.pack()

titleCanvas.create_image(10,10,anchor=NW,image=titleImage)

# display background image
background = ImageTk.PhotoImage(Image.open(path + 'background image.png'))
backgroundCanvas = Canvas(root, width=screen_width, height = screen_height-70)
backgroundCanvas.pack()

backgroundCanvas.create_image(10,10, anchor=NW, image =background)

root.mainloop(0)

如何让标题透明化?

【问题讨论】:

  • PNG 不允许透明。
  • @Xitiz 你是什么意思 png 是透明的?
  • @SamLeighton 我认为您对 PNG 透明的看法是正确的。 tkinter.Labels 也不允许透明度。尝试改用tkinter.Canvas
  • 你的PNG透明吗?这不仅仅是“发生”,它必须被标记。格式本身确实支持它,en.wikipedia.org/wiki/…
  • @TheLizzard 你介意向我解释一下画布是如何工作的吗?我有点 tkinter noob

标签: python tkinter


【解决方案1】:

你可以像这样使用Canvas

img= ImageTk.PhotoImage(Image.open(path + 'background image.png'))

canvas= Canvas(root, width= 600, height= 400)
canvas.pack()

#Add image to the Canvas Items
canvas.create_image(0,0,anchor=NW,image=img)

我们只是在变量中创建 Canvas canvas 并在其中添加图像 img

编辑: 根据 OP 代码:

titleImage= ImageTk.PhotoImage(Image.open(path + 'clash clan manager text.png'))
background = ImageTk.PhotoImage(Image.open(path + 'background image.png'))

canvas= Canvas(root, width= 600, height= 400)
canvas.pack()

canvas.create_image(0,0, image =titleImage)
canvas.create_image(0,<change position according to title image size or 0 if you want to put title in background image>, image =background)

我们将titleImage放在第一位,背景放在最后。

我的输出:

【讨论】:

  • 非常感谢,这行得通!如果您不介意,您能否快速解释一下创建图像功能中的“10”和“锚”部分是什么?
  • 我刚刚意识到,它仍然不能使图像透明:(
  • 这 10 个是图像的位置。表示图像应该放在哪里。您可以使用 19 的 0,0。前 10 个用于 x 轴,第二个用于 y 轴。锚点用于定义图像相对于参考点的位置。那里 NW 意味着西北
  • 谢谢。你知道它为什么不透明吗?
  • 我认为这一定是我的代码所在的顺序,我实际上不确定。我只是像你一样重新订购了它,它修复了它。
猜你喜欢
  • 1970-01-01
  • 2011-03-17
  • 2012-07-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-12
  • 2010-10-16
  • 2011-10-14
相关资源
最近更新 更多