如何在Tkinter中添加图像?
图像在任何应用程序中都是非常有用的对象。我们可以使用Python中的Pillow或PIL包在Tkinter应用程序中处理图像。有几个内置函数,例如加载图像,提取图像,配置图像窗格等。
示例
在此示例中,我们将通过要求用户从对话框中选择图像,然后使用Label小部件显示它来添加图像。
#导入Tkinter库
from tkinter import *
from tkinter import ttk
from tkinter import filedialog
from PIL import Image, ImageTk
#创建Tkinter帧的实例
win= Tk()
#定义几何体
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()
#创建标签和按钮以打开对话框
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()
输出
运行上述代码将显示一个窗口,其中包含一个按钮,用于从目录中选择图像文件并在窗口上显示图像。
现在,从本地目录中选择任何图像并在屏幕上显示输出。