如何在 Tkinter 中将背景图像调整为窗口大小?
为了处理图像,Python 库提供了 Pillow 或 PIL 包,它使应用程序能够导入图像并在其上执行各种操作。
假设我们想要将图像动态调整为窗口大小。在这种情况下,我们必须遵循以下步骤——
在 Tkinter 应用程序中打开图像。
创建一个 Canvas 窗口小组件并使用 create_image(**options) 将加载的图像放置在画布中。
定义一个函数来调整已加载图像的大小。
将该函数与父窗口配置绑定。
示例
# Import the required libraries
from tkinter import *
from PIL import ImageTk, Image
# Create an instance of Tkinter Frame
win = Tk()
# Set the geometry of Tkinter Frame
win.geometry("700x450")
# Open the Image File
bg = ImageTk.PhotoImage(file="tutorialspoint.png")
# Create a Canvas
canvas = Canvas(win, width=700, height=3500)
canvas.pack(fill=BOTH, expand=True)
# Add Image inside the Canvas
canvas.create_image(0, 0, image=bg, anchor='nw')
# Function to resize the window
def resize_image(e):
global image, resized, image2
# open image to resize it
image = Image.open("tutorialspoint.png")
# resize the image with width and height of root
resized = image.resize((e.width, e.height), Image.ANTIALIAS)
image2 = ImageTk.PhotoImage(resized)
canvas.create_image(0, 0, image=image2, anchor='nw')
# Bind the function to configure the parent window
win.bind("<Configure>", resize_image)
win.mainloop()输出
运行上述代码会显示一个包含图像的窗口,该图像可以动态调整大小。

广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 程序设计
C++
C#
MongoDB
MySQL
Javascript
PHP