«Tkinter filedialog.askopenfile create a modal, native look-and-feel dialog for user to select and upload file from local system. .
Tkinter filedialog to read upload and adjust height width to resize multiple images to display
We will use askopenfilename() to open the local file browser and by which user will select one image file and on submit the image will be displayed in the Tkinter window.
import tkinter as tk
from tkinter import filedialog
from tkinter.filedialog import askopenfile
Here is the code to open one file browser dialog box and then select a file to upload. After uploading the image will be displayed in the Tkinter window.
import tkinter as tk
from tkinter import filedialog
from tkinter.filedialog import askopenfile
from PIL import Image, ImageTk
my_w = tk.Tk()
my_w.geometry("400x300") # Size of the window
my_w.title('www.plus2net.com')
my_font1=('times', 18, 'bold')
l1 = tk.Label(my_w,text='Add Student Data with Photo',width=30,font=my_font1)
l1.grid(row=1,column=1)
b1 = tk.Button(my_w, text='Upload File',
width=20,command = lambda:upload_file())
b1.grid(row=2,column=1)
def upload_file():
global img
f_types = [('Jpg Files', '*.jpg')]
filename = filedialog.askopenfilename(filetypes=f_types)
img = ImageTk.PhotoImage(file=filename)
b2 =tk.Button(my_w,image=img) # using Button
b2.grid(row=3,column=1)
my_w.mainloop() # Keep the window open
We kept three images in one row, we are resizing the images before displaying.
Full code is here
import tkinter as tk
from tkinter import *
from tkinter import filedialog
from tkinter.filedialog import askopenfile
from PIL import Image, ImageTk
my_w = tk.Tk()
my_w.geometry("410x300") # Size of the window
my_w.title('www.plus2net.com')
my_font1=('times', 18, 'bold')
l1 = tk.Label(my_w,text='Upload Files & display',width=30,font=my_font1)
l1.grid(row=1,column=1,columnspan=4)
b1 = tk.Button(my_w, text='Upload Files',
width=20,command = lambda:upload_file())
b1.grid(row=2,column=1,columnspan=4)
def upload_file():
f_types = [('Jpg Files', '*.jpg'),
('PNG Files','*.png')] # type of files to select
filename = tk.filedialog.askopenfilename(multiple=True,filetypes=f_types)
col=1 # start from column 1
row=3 # start from row 3
for f in filename:
img=Image.open(f) # read the image file
img=img.resize((100,100)) # new width & height
img=ImageTk.PhotoImage(img)
e1 =tk.Label(my_w)
e1.grid(row=row,column=col)
e1.image = img
e1['image']=img # garbage collection
if(col==3): # start new line after third column
row=row+1# start wtih next row
col=1 # start with first column
else: # within the same row
col=col+1 # increase to next column
my_w.mainloop() # Keep the window open