2014-06-05 170 views
6

尝试为我的tkinter窗口设置背景。我有一个正方形的背景图像,在边缘变黑,然后主窗口变成黑色背景。图像放置在背景上,如果窗口宽度比高度大,则图像在黑色背景中间居中,而且看起来非常漂亮。Tkinter将窗口大小调整为背景图像(Python 3.4)

但是,当窗口的宽度和高度小于图像的宽度和高度时,它将图像的中心放在窗口的中心,因此看不到整个图像,而且看起来有点奇怪。是否有一种调整图像大小的方法,以便如果窗口的宽度和高度最大值小于图像大小,则将图像调整为该大小,以保持宽高比。

所以说,背景图像是600x600

  • 800x400窗口,图像不会调整大小,和垂直中心本身。
  • 500x400窗口中,图像调整为500x500,并且仍然垂直居中。
  • 400x900窗口中,图像不会调整大小,并且水平居中。

居中功能已经存在,我只需要调整大小功能。

目前我有什么是:

from tkinter import * 

root = Tk() 
root.title("Title") 
root.geometry("600x600") 
root.configure(background="black") 

background_image = PhotoImage(file="Background.gif") 

background = Label(root, image=background_image, bd=0) 
background.pack() 

root.mainloop() 

不知道是否有在Tkinter的这样的一种方式?或者,如果可能我会编写自己的函数,根据窗口大小调整图像大小,但是如果用户在任何点调整窗口大小,则图像需要相对平滑且快速地调整大小。

+0

使用[pillow](http://pillow.readthedocs.org/en/latest/)进行图像大小调整。 – Marcin

回答

10

这是一个使用枕头作为标签更改大小来调整在标签图像示例应用程序:

from tkinter import * 

from PIL import Image, ImageTk 

root = Tk() 
root.title("Title") 
root.geometry("600x600") 
root.configure(background="black") 



class Example(Frame): 
    def __init__(self, master, *pargs): 
     Frame.__init__(self, master, *pargs) 



     self.image = Image.open("./resource/Background.gif") 
     self.img_copy= self.image.copy() 


     self.background_image = ImageTk.PhotoImage(self.image) 

     self.background = Label(self, image=self.background_image) 
     self.background.pack(fill=BOTH, expand=YES) 
     self.background.bind('<Configure>', self._resize_image) 

    def _resize_image(self,event): 

     new_width = event.width 
     new_height = event.height 

     self.image = self.img_copy.resize((new_width, new_height)) 

     self.background_image = ImageTk.PhotoImage(self.image) 
     self.background.configure(image = self.background_image) 



e = Example(root) 
e.pack(fill=BOTH, expand=YES) 


root.mainloop() 

这是它的工作原理使用Lenna图像为例:

enter image description here

+2

你可以[跳过调整大小的事件,请参阅'fit_image()'方法](https://gist.github.com/zed/8b05c3ea0302f0e2c14c#file-slideshow-py-L47) – jfs

4

我修改了上面的代码,所以它不在一个类

#!/usr/bin/python3.5 

from tkinter import * 
from tkinter import ttk 
from PIL import Image, ImageTk 

root = Tk() 
root.title("Title") 
root.geometry('600x600') 

def resize_image(event): 
    new_width = event.width 
    new_height = event.height 
    image = copy_of_image.resize((new_width, new_height)) 
    photo = ImageTk.PhotoImage(image) 
    label.config(image = photo) 
    label.image = photo #avoid garbage collection 

image = Image.open('image.gif') 
copy_of_image = image.copy() 
photo = ImageTk.PhotoImage(image) 
label = ttk.Label(root, image = photo) 
label.bind('<Configure>', resize_image) 
label.pack(fill=BOTH, expand = YES) 

root.mainloop()