如何在 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