Ttk背景图像

时间:2016-04-15 20:50:22

标签: python python-2.7 tkinter ttk

有没有办法使用PIL将图像导入python并将其设置为跨越整个Tkinter根窗口的ttk主机的背景?截至目前,我只看到过这样做的方法是Tkinter root。还有什么方法可以让ttk自我调整图像的大小,这样即使它很小也覆盖整个屏幕?

总而言之,我想要一个图像覆盖整个ttk主机框,而不会让我把任何其他东西放在ttk框架中。

例如,

如果pic覆盖了整个窗口,那么命令

ttk.Button(root, text="Hello").grid(column=0, row=0, sticky=(N,S,W,E))

仍然会在主机中插入一个按钮。谢谢:))

1 个答案:

答案 0 :(得分:2)

您无法将图像背景设置为ttk帧,但它们不接受图像选项。所以你可以制作一个ttk框架并在其中放置一个标签或其他东西,然后让它跨越框架,以适应下面的例子。

这是一个展示你想要的小例子。我们用pil加载图像,注意链接的图像比屏幕尺寸小(我希望)。

因此,我们将根窗口的几何图形设置为图像小于此值的整个屏幕,因此我们将其大小调整为覆盖整个宽度。您可以覆盖最大和最小高度,然后根据此设置它。只是一个样本值。然后我们将bg标签和网格小部件放在它上面。标签的堆叠顺序低于您将使用网格放置的其他小部件,因此它们显示在顶部。或者,您可以使用画布或其他小部件。使用画布,您必须使用create_window将小部件放在画布中。

import tkinter as tk
from tkinter import ttk
from PIL import Image, ImageTk

root = tk.Tk()
width, height = root.winfo_screenwidth(), root.winfo_screenheight()
#print(root.winfo_screenheight(), root.winfo_screenwidth())
root.geometry("%dx%d" % (width, height))
#URL FOR BACKGROUND
#https://www.google.com/url?sa=i&rct=j&q=&esrc=s&source=images&cd=&ved=0ahUKEwiVroCiyZHMAhXKeT4KHQHpDVAQjBwIBA&url=http%3A%2F%2Fwallpaperswide.com%2Fdownload%2Fblack_background_metal_hole_very_small-wallpaper-800x480.jpg&psig=AFQjCNEjZ7GDbjG9sFie-yXW3fP85_p0VQ&ust=1460840934258935
image = Image.open("background.jpg")
if image.size != (width, height):
    image = image.resize((width, height), Image.ANTIALIAS)
    #print("DONE RESIZING")
    # image.save("background.jpg")
#print(image.size)
image = ImageTk.PhotoImage(image)
bg_label = tk.Label(root, image = image)
bg_label.place(x=0, y=0, relwidth=1, relheight=1)
bg_label.image = image
your_button = ttk.Button(root, text='This is a button')
your_button.grid()
root.mainloop()