Tom*_*mha 9 python tkinter python-3.x
试图为我的tkinter窗口设置背景.我有一个方形的背景图像,边缘渐渐变黑,然后主窗口有黑色背景.图像被放置在背景上,如果窗口比它高,那么图像中心位于黑色背景的中间,看起来非常漂亮.
但是当窗口小于图像的宽度和高度时,它会将图像的中心放在窗口的中心,因此您看不到整个图像,看起来有点奇怪.有没有办法调整图像的大小,以便如果窗口的最大宽度和高度小于图像,图像将调整到该大小,保持纵横比.
所以说背景图片是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()
Run Code Online (Sandbox Code Playgroud)
不确定在tkinter中是否有办法这样做?或者,如果我可能会根据窗口大小编写自己的调整图像大小的函数,但是如果用户在任何时候调整窗口大小,图像需要相对平滑且快速地调整大小.
Mar*_*cin 14
这是一个示例应用程序,当标签更改大小时,使用Pillow调整Label上的图像大小:
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()
Run Code Online (Sandbox Code Playgroud)
这是使用Lenna图像作为示例的工作原理:

小智 6
我已经修改了上面的代码,所以它不在一个类中
#!/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()
Run Code Online (Sandbox Code Playgroud)