【问题标题】:PNG Image transparency in tkintertkinter中的PNG图像透明度
【发布时间】:2020-06-06 04:26:57
【问题描述】:

我一直在尝试在 tkinter 中显示带有透明部分的 .PNG 图像。但我遇到了一个问题。在显示图像时,它往往会失去透明度。有什么办法可以解决这个问题吗?
我是 tkinter 的新手,但精通 pygame,我已经在 pygame 中应用了这个想法,它似乎很有效。

这是我目前写的代码:

from tkinter import *
from tkinter import ttk
import tkinter.font as tkfont
from PIL import ImageTk,Image

root = Tk()
root.title("Kiara")
root.geometry("706x462")

#Images
home_button_image = ImageTk.PhotoImage(Image.open("E:/Kiara Project/Screens/home_button.png"))
note_button_image = ImageTk.PhotoImage(Image.open("E:/Kiara Project/Screens/note_button.png"))
about_button_image = ImageTk.PhotoImage(Image.open("E:/Kiara Project/Screens/about_button.png"))
menu_home_activated_image = ImageTk.PhotoImage(Image.open("E:/Kiara Project/Screens/menu_home_activated.png"))

#Buttons
home_button = Button(root, image=home_button_image, bd=0)
note_button = Button(root, image=note_button_image, bd=0)
about_button = Button(root, image=about_button_image, bd=0)

#Screens
menu_home_activated = Label(root, image=menu_home_activated_image, bd=0)

menu_home_activated.place(x=0, y=0)
note_button.place(x=300, y=50)

root.update()

root.mainloop()

这是输出:

menu_home_activated.png 与 tkinter 窗口大小相同,并且除了在输出中可见的部分之外是透明的。
如您所见,note_button 即使放在透明部分也不会显示。

如果有帮助,我正在使用 Python 3.8.3。

【问题讨论】:

  • tkinter LabelButton 不支持透明图像。只有Canvas.create_image() 可以。
  • 你能提供一个例子来说明如何在我的情况下使用它吗?
  • 我不知道为什么note_button没有显示,因为它放在标签之后,即它应该显示在标签的顶部。
  • 我已经添加了两个.png文件,如果你想试试看!!
  • 好的...我现在明白了!谢谢你的帮助!!

标签: python python-3.x tkinter pygame python-imaging-library


【解决方案1】:

抱歉,这有点太大了,无法发表评论,也不是完整的答案

我不认为你应该需要ImageTk. 尝试运行这个:(我不能,因为我不知道你想要它看起来像什么,而且我的电脑上没有这些文件)

from tkinter import * 
from tkinter.ttk import *  
root = Tk() 

# Creating photoimage objects to use in the buttons
home_button_image = PhotoImage(file = r"E:/Kiara Project/Screens/home_button.png")
note_button_image = PhotoImage(file = r"E:/Kiara Project/Screens/note_button.png")
about_button_image = PhotoImage(file = r"E:/Kiara Project/Screens/about_button.png")
menu_home_activated_image = PhotoImage(file = r"E:/Kiara Project/Screens/menu_home_activated.png")

# Making the buttons
home_button = Button(root, image = home_button_image).pack(side = TOP)
note_button = Button(root, image = note_button_image).pack(side = TOP)
about_button = note_button = Button(root, image = about_button_image).pack(side = TOP)

# Screens
lable = lable(root, image = menu_home_activated_image)
label.pack

root.update()

mainloop()

我不能保证这会起作用,但它会稍微清理一下代码,而且这有点匆忙,所以可能会有一些错误

【讨论】:

  • 在编写我在问题中给出的代码之前,我已经尝试过这个,它不起作用。它产生相同的输出。无论如何,感谢您的回复。
  • 不要在同一行创建小部件和打包小部件。 home_button etc. 都将是 None
猜你喜欢
  • 2016-02-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-10
  • 1970-01-01
相关资源
最近更新 更多