python - Tkinter 将背景图像调整为窗口大小

标签 python python-3.x tkinter

正在尝试为我的 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()

不确定在 tkinter 中是否有这样做的方法?或者,如果我可能会编写自己的函数来根据窗口大小调整图像大小,但是如果用户在任何时候调整窗口大小,图像需要相对平滑和快速地调整大小。

最佳答案

这是一个示例应用程序,它使用 Pillow 在标签更改大小时调整标签上的图像大小:

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

关于python - Tkinter 将背景图像调整为窗口大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24061099/

相关文章:

python - 如何使用python删除excel中的所有零值

python - 如何将 stringVar() 从 tk 转换为 pyqt

python - 在 Python 中声明未知类型变量?

python :How to generate a power law graph

python - for循环内和for循环外声明变量的区别

python - 根据另一列中的组和条件填充列

python - 将 FASTA 文件中的多个序列添加到 python 列表中

python - 什么是变量注解?

python - Tkinter:列表框分隔符、禁用项、键盘导航?

python - tkinter 如何在任何系统上打开特定文件夹(也包含 .py 脚本)的文件目录?