如何使tkinter标签的背景透明?

15
我有一个带标签的窗口作为我的框架。我这么做是因为我想要在背景中放置一张图片。但是现在,我用的其他标签出了问题。我用来实际标记事物的其他标签没有透明的背景。是否有办法使这些标签的背景透明?

我有一个窗口,使用标签作为窗口的外观。我这样做是因为我想要在背景中放置一张图片。但现在,我遇到了使用其他标签时出现的问题。我用来标记实际事物的其他标签没有透明的背景。是否有办法使这些标签的背景透明?

import Tkinter as tk

root = tk.Tk()
root.title('background image')

image1 = Tk.PhotoImage(file='image_name.gif')

# get the image size
w = image1.width()
h = image1.height()

# make the root window the size of the image
root.geometry("%dx%d" % (w, h))

# root has no image argument, so use a label as a panel
panel1 = tk.Label(root, image=image1)
panel1.pack(side='top', fill='both', expand='yes')

# put a button/label on the image panel to test it
label1 = tk.Label(panel1, text='here i am')
label1.pack(side=Top)

button2 = tk.Button(panel1, text='button2')
button2.pack(side='top')

# start the event loop
root.mainloop()
4个回答

10

我认为这可以帮助你,所有的黑色都会变成透明的。

root.wm_attributes('-transparentcolor','black')

6
使用 root.wm_attributes('-transparentcolor', root['bg']) 来使默认颜色透明。 - Nae
4
如果仅使有颜色的小部件透明,那将是一个很好的解决方案,但似乎会使有颜色的小部件及所有位于其下方的小部件都变为透明。如果能够使提升的小部件透明并看到比它更低的小部件,那就太好了。你有什么办法可以实现这一点吗? - GaryMBloom
1
这个功能非常好用,可以将特定颜色变为透明,但是有两个主要问题:a)像Gary02127所说的那样,它会使所有小部件都变成透明的,但似乎(至少在Windows 10上)它也会使所有具有指定颜色的区域变得可渗透。 - Nummer_42O
7
不起作用,我已经尝试过了,它不接受“-transparentcolor”作为第一个参数。 - cs1349459

6

Tk不支持透明背景。


5
如果您正在处理图像并在其上放置文本,则最方便的方式是使用Canvas小部件。 tkinter Canvas小部件具有.create_image(x, y, image=image, options).create_text(x, y, text="Some text", options)方法。

2
使用这个:
from tkinter import *

main=Tk()
photo=PhotoImage(file='test.png')
Label(main,image=photo,bg='grey').pack()
#your other label or button or ...
main.wm_attributes("-transparentcolor", 'grey')
main.mainloop()

如果使用bg='grey',这个工作就会生效。你可以在第七行更改它。

祝你好运 :)


3
_tkinter.TclError: 错误的属性“-transparentcolor”:必须是-alpha、-fullscreen、-modified、-notify、-titlepath、-topmost或-transparent。不起作用。 - exec85
14
这很有趣,但它在整个应用程序中切了一个洞,让桌面显示在窗口后面。 - codingCat
它对我来说有效,但问题是由于某种原因,文本或图像周围出现了一个像素化的灰色轮廓。 - 5alidshammout

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接