如何使用 photoimage 对象在 Tkinter 中使用图像?


Python 支持 PIL 或 Pillow 包,这是一个开源库,用于在 Python 项目中打开、处理和保存不同格式的图像。我们可以在 Tkinter 应用程序中使用它来处理和显示图像。

Tkinter 中的 Label 组件用于在 Tkinter 应用程序中渲染文本和图像。要使用 Tkinter 应用程序中的 Label 组件显示图像,我们可以按照以下步骤操作:

  • 确保系统中已安装 Pillow 或 PIL 包。

  • 使用 ImageTk.PhotoImage(file=file_location) 函数在变量中加载图像。

  • 创建一个 Label 组件,将图像值分配为图像。

  • 执行代码以显示图像。

示例

# Import the required libraries
from tkinter import *
from PIL import Image, ImageTk

# Create an instance of tkinter frame or window
win=Tk()

# Set the size of the window
win.geometry("700x470")

# load the image and convert it into Tkinter Photoimage
bg=ImageTk.PhotoImage(file="baseball.png")

# Add a label widget to display the image
label=Label(win, image=bg)
label.place(x=0, y=0)

win.mainloop()

输出

运行代码以在 Tkinter 窗口中显示图像。

更新于: 19-6-2021

5K+ 浏览

启动您的 职业

通过完成课程获得认证

开始
广告
© . All rights reserved.