Loading Images in Tkinter using PIL
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 –
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 –
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 –
The openfilename function will return the file name of image.
Function to return the file name chosen from a dialog box –
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 –
and press enter and it will run. Or can be run directly by simply double-clicking your .py extension file.