用tkinter做一个从本地上传两张图片并显示的界面
时间: 2023-06-06 19:04:51 浏览: 488
详解python tkinter包获取本地绝对路径(以获取图片并展示)
可以的,这是一个很好的问题!您可以使用Tkinter的文件对话框获取用户选择的图像文件,然后使用Pillow库加载和显示图像。以下是一个示例代码,希望能对您有所帮助:
```
from tkinter import *
from tkinter import filedialog
from PIL import Image, ImageTk
class ImageUploader:
def __init__(self, master):
self.master = master
master.title("Image Uploader")
self.image1 = None
self.image2 = None
self.label1 = Label(master, text="Image 1:")
self.label1.grid(row=0, column=0)
self.label2 = Label(master, text="Image 2:")
self.label2.grid(row=1, column=0)
self.button1 = Button(master, text="Upload", command=self.upload_image1)
self.button1.grid(row=0, column=2)
self.button2 = Button(master, text="Upload", command=self.upload_image2)
self.button2.grid(row=1, column=2)
self.canvas1 = Canvas(master, width=300, height=300)
self.canvas1.grid(row=0, column=1)
self.canvas2 = Canvas(master, width=300, height=300)
self.canvas2.grid(row=1, column=1)
def upload_image1(self):
file_path = filedialog.askopenfilename()
if file_path:
self.image1 = Image.open(file_path)
self.image1 = self.image1.resize((300, 300))
self.photo1 = ImageTk.PhotoImage(self.image1)
self.canvas1.create_image(0, 0, anchor=NW, image=self.photo1)
def upload_image2(self):
file_path = filedialog.askopenfilename()
if file_path:
self.image2 = Image.open(file_path)
self.image2 = self.image2.resize((300, 300))
self.photo2 = ImageTk.PhotoImage(self.image2)
self.canvas2.create_image(0, 0, anchor=NW, image=self.photo2)
root = Tk()
image_uploader = ImageUploader(root)
root.mainloop()
```
这个例子创建了一个简单的GUI界面,其中有两个按钮,用于上传两个图像文件,以及两个Canvas,用于显示这些图像。当用户单击“Upload”按钮时,文件对话框将弹出,用户可以选择要上传的图像文件。然后,程序使用Pillow库打开图像文件,并将其调整大小以适应Canvas的大小。最后,图像被加载到Canvas中并显示给用户。
阅读全文