如何在 Tkinter 中添加图像?


图像在任何应用程序中都是非常有用的对象。我们可以使用 Python 中的 Pillow 或者 PIL 包在 Tkinter 应用程序中处理图像。有若干内置函数,如加载图像、提取图像、配置图像窗格等。

示例

在这个示例中,我们将通过让用户从一个对话框中选择一张图像,然后使用 Label 控件显示它来添加图像。

#Import the Tkinter library
from tkinter import *
from tkinter import ttk
from tkinter import filedialog
from PIL import Image, ImageTk
#Create an instance of Tkinter frame
win= Tk()
#Define the geometry
win.geometry("750x350")
win.title("Image Gallery")
def select_file():
   path= filedialog.askopenfilename(title="Select an Image", filetype=(('image    files','*.jpg'),('all files','*.*')))
   img= Image.open(path)
   img=ImageTk.PhotoImage(img)
   label= Label(win, image= img)
   label.image= img
   label.pack()
#Create a label and a Button to Open the dialog
Label(win, text="Click the Button below to select an Image", font=('Caveat 15 bold')).pack(pady=20)
button= ttk.Button(win, text="Select to Open", command= select_file)
button.pack(ipadx=5, pady=15)
win.mainloop()

输出

运行上述代码将显示一个窗口,其中包含一个按钮,用于从目录中选择图像文件,并在窗口上显示图像。

现在,从本地目录中选择任意一张图像,并在屏幕上显示输出。

更新日期:2021 年 4 月 21 日

3K+ 浏览量

开启你的职业生涯

完成课程,获得认证

入门指南
广告
© . All rights reserved.