Python Tkinter 背景图片设置教程 - 使用 Pillow 库
要在 Tkinter 中插入背景图片,可以使用 Pillow 库(也称为 PIL)来加载和显示图像。以下是一个简单的代码示例:
from tkinter import *
from PIL import Image, ImageTk
root = Tk()
# 加载图片并调整大小
image = Image.open('background.jpg')
image = image.resize((600, 400), Image.ANTIALIAS)
# 将图像转换为 Tkinter 中的 PhotoImage 对象
photo = ImageTk.PhotoImage(image)
# 创建标签并将图像放入其中
label = Label(root, image=photo)
label.pack()
root.mainloop()
在此示例中,我们使用 Pillow 库中的 Image.open() 函数来打开图像文件,并使用 Image.resize() 函数调整其大小。接下来,我们使用 ImageTk.PhotoImage() 函数将图像转换为 Tkinter 中的 PhotoImage 对象。最后,我们创建一个标签并使用 Label() 函数将图像放入其中,然后使用 pack() 函数将标签放置在窗口中。
请注意,ImageTk.PhotoImage() 函数只能在全局范围内使用,否则可能会出现垃圾回收问题。因此,我们必须将其分配给一个变量,以便在整个程序中引用它。
原文地址: https://www.cveoy.top/t/topic/ocMQ 著作权归作者所有。请勿转载和采集!