用tkinter设置背景图像

时间:2012-05-03 19:23:50

标签: tkinter

我有一个带按钮,标签,文本框等的gui,我想把它全部放在背景图像上(比如猫王的脸),就像桌面一样。我喜欢这样,文本框和标签不会阻挡图像,而是文本位于图像上,图像保持完全可见。有什么建议吗?

1 个答案:

答案 0 :(得分:1)

好的,所以考虑到一些警告,我已经完成了这项工作。首先,我没有打算尝试使用ttk小部件,因为我还没有达到速度。其次,我知道这适用于Windows,并且非常确定它不适用于其他平台。所有这一切,诀窍是在你的图像上弹出一个Toplevel窗口(在我的代码中命名为叠加),将其配置为透明色(显然只能在Windows Tk中使用),然后将小部件放在叠加层上并设置它们的透明色背景(代码中的trans_color)。我还会捕获根<Configure>事件以保持叠加层。对于图像,我只是右键单击了您的个人资料图像并将其保存到磁盘(命名为spice.png)。

from Tkinter import *
#from ttk import *
from PIL import Image, ImageTk

trans_color = '#FFFFFE'

root = Tk()
img = ImageTk.PhotoImage(Image.open('spice.png'))
img_label = Label(root, image=img)
img_label.pack()
img_label.img = img  # PIL says we need to keep a ref so it doesn't get GCed
root.update()
overlay = Toplevel(root)
print 'root.geo=', root.geometry()
geo = '{}x{}+{}+{}'.format(root.winfo_width(), root.winfo_height(),
    root.winfo_rootx(), root.winfo_rooty())
print 'geo=',geo
overlay.geometry(geo)
overlay.overrideredirect(1)
overlay.wm_attributes('-transparent', trans_color)
overlay.config(background=trans_color)

lbl = Label(overlay, text='LABEL')
lbl.config(background=trans_color)
lbl.pack()

def moved(e):
    geo = '{}x{}+{}+{}'.format(root.winfo_width(), root.winfo_height(),
        root.winfo_rootx(), root.winfo_rooty())
    overlay.geometry(geo)

root.bind('<Configure>', moved)

root.mainloop()