要在Tkinter中插入图片,可以使用PIL(Python Imaging Library)模块。以下是一个示例代码,可以在窗口中显示一个图片:

from tkinter import *
from PIL import ImageTk, Image

root = Tk()

# 打开图片文件
image = Image.open("example.jpg")

# 将图片转换为Tkinter支持的格式
photo = ImageTk.PhotoImage(image)

# 创建一个Label组件,并将图片设置为它的背景
label = Label(root, image=photo)
label.pack()

root.mainloop()

在上面的代码中,我们首先使用Image.open()函数打开一个图片文件,然后将它转换为Tkinter支持的格式。这里我们使用了ImageTk.PhotoImage()函数来实现。最后,我们创建了一个Label组件,并将图片设置为它的背景,然后将它添加到窗口中。

需要注意的是,PhotoImage对象必须在程序中保持引用,否则它会被Python的垃圾回收机制自动清除,导致图片无法显示

tkinter插入图片

原文地址: https://www.cveoy.top/t/topic/gKc3 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录