Tkinter - 按钮图像透明背景
问题描述:
我已经研究出了如何为按钮设置图像,即定位在标签顶部(我想我可能会这样做,因为我无法安装PIL我的Mac出于某种原因)。无论如何,它在某种程度上应该起作用 - 我遇到的问题是它会在任何一方添加空白区域,然后图像本身不会显示其透明背景。Tkinter - 按钮图像透明背景
我使用的代码如下:
from tkinter import *
#from PIL import Image
root = Tk()
#Removes the title bar and places over mac top bar
root.tk.call("::tk::unsupported::MacWindowStyle", "style", root._w, "plain", "none")
# Makes the app full screen
#root.wm_attributes('-fullscreen', 1)
root.geometry('{}x{}'.format(480, 320))
#root.attributes('-topmost', True)
def quitApp():
# mlabel = Label (root, text = 'Close').pack()
root.destroy()
background_img = PhotoImage(file="images/bg.gif")
scanBtn_img = PhotoImage(file="images/scanBtn.gif")
background = Label(root,
compound = CENTER,
quitButton = Button(image=scanBtn_img, command = quitApp).pack(),
image = background_img).pack(side="right")
background.image = background_img # keep a reference!
root.mainloop()
答
从我了解的Tkinter本身支持像GIF图像的透明度。
我把你的代码切碎了一点,但它确实对我有用。也许在设置代码方面存在问题。您的标签中还有一个按钮。我不认为你需要两者都有。你可以在你想要的地方创建按钮。
仅供参考,我在黑色背景的不同侧面上创建了一个标签和一个按钮,以显示图像的透明度。
这是我用来测试gif
的代码我有透明度。为了以防万一,我在python 3.6和2.7上测试了这个。
from tkinter import *
root = Tk()
def quitApp():
root.destroy()
background_img = PhotoImage(file="Colors/sa.gif")
scanBtn_img = PhotoImage(file="Colors/sa.gif")
background = Label(root,bg='black', image = background_img).pack(side = RIGHT)
quitButton = Button(bg='black', image=scanBtn_img, command = quitApp).pack(side = LEFT)
backgroundimage = background_img # keep a reference!
root.mainloop()
更新:我用您的评论
链接GIF下面是结果。
更新:
后做一些更多的挖我找到了可能用于Mac OS工作:
我没有一台Mac,现在来测试,所以让我知道如果这适用于你:
from tkinter import *
root = Tk()
# Hide the root window drag bar and close button
root.overrideredirect(True)
# Make the root window always on top
root.wm_attributes("-topmost", True)
# Make the window content area transparent
root.wm_attributes("-transparent", True)
# Set the root window background color to a transparent color
root.config(bg='systemTransparent')
def quitApp():
root.destroy()
background_img = PhotoImage(file="Colors/1.gif")
scanBtn_img = PhotoImage(file="Colors/1.gif")
background = Label(root,bg='black', image = background_img).pack(side = RIGHT)
background.config(bg='systemTransparent')
quitButton = Button(bg='black', image=scanBtn_img, command = quitApp).pack(side = LEFT)
quitButton.config(bg='systemTransparent')
backgroundimage = background_img # keep a reference!
root.mainloop()
你确定你在Python 2.7,因为你导入tkinter小写为python 3. –