In this article, we will learn how to load images from user system to Tkinter window using PIL module. This program will open a dialogue box to select the required file from any directory and display it in the tkinter window.
Install the requirements –
Use this command to install Tkinter :
pip install python-tk
Use this command to install PIL :
pip install pillow
Importing modules –
Python3
from tkinter import *
from PIL import ImageTk, Image
from tkinter import filedialog
|
Note: The ImageTk module contains support to create and modify Tkinter BitmapImage and PhotoImage objects from PIL images and filedialog is used for the dialog box to appear when you are opening file from anywhere in your system or saving your file in a particular position or place.
Function to create a Tkinter window consisting of a button –
Python3
root = Tk()
root.title( "Image Loader" )
root.geometry( "550x300 + 300 + 150" )
root.resizable(width = True , height = True )
btn = Button(root, text = 'open image' , command = open_img).grid(
row = 1 , columnspan = 4 )
root.mainloop()
|
The Button object is created with text ‘open image’. On clicking it the open_image function will be invoked.
Function to place the image onto the window –
Python3
def open_img():
x = openfilename()
img = Image. open (x)
img = img.resize(( 250 , 250 ), Image.ANTIALIAS)
img = ImageTk.PhotoImage(img)
panel = Label(root, image = img)
panel.image = img
panel.grid(row = 2 )
|
The openfilename function will return the file name of image.
Function to return the file name chosen from a dialog box –
Python3
def openfilename():
filename = filedialog.askopenfilename(title = '"pen' )
return filename
|
To run this code, save it by the extension .py and then open cmd (command prompt) and move to the location of the file saved and then write the following –
python "filename".py
and press enter and it will run. Or can be run directly by simply double-clicking your .py extension file.
Output:
https://media.geeksforgeeks.org/wp-content/uploads/20191121233525/Screencast-from-Thursday-21-November-2019-111137-IST2.webm
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
06 Aug, 2022
Like Article
Save Article