Browse Upload & Display Image in Tkinter

Tkinter
filedialog.askopenfile create a modal, native look-and-feel dialog for user to select and upload file from local system. .

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.
Upload and display photo
import tkinter as tk
from tkinter import filedialog
from tkinter.filedialog import askopenfile
File Upload Browser
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
Output is here ( based on the uploaded file )

Image resizing before displaying

Based on the requirement we can change the dimension of the uploaded image and then display the same.
More in resizing Image using PIL
def upload_file():
    global img
    f_types = [('Jpg Files', '*.jpg')]
    filename = filedialog.askopenfilename(filetypes=f_types)
    img=Image.open(filename)
    img_resized=img.resize((400,200)) # new width & height
    img=ImageTk.PhotoImage(img_resized)
    b2 =tk.Button(my_w,image=img) # using Button 
    b2.grid(row=3,column=1)
Reading width and height of uploaded image and then resizing to maintain aspect ration
	img=Image.open(filename)
	width, height = img.size  
	width_new=int(width/3)
	height_new=int(height/3)
	img_resized=img.resize((width_new,height_new))

Tkinter window to upload and insert image to MySQL Blob Data column
Tkinter Filedialog Treeview asksaveasfile()

Subscribe

* indicates required
Subscribe to plus2net

    plus2net.com



    Post your comments , suggestion , error , requirements etc here





    Python Video Tutorials
    Python SQLite Video Tutorials
    Python MySQL Video Tutorials
    Python Tkinter Video Tutorials
    We use cookies to improve your browsing experience. . Learn more
    HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
    ©2000-2021 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer