Save Image To File in Python using Tkinter
Last Updated :
26 Feb, 2024
Saving an uploaded image to a local directory using Tkinter combines the graphical user interface capabilities of Tkinter with the functionality of handling and storing images in Python. In this article, we will explore the steps involved in achieving this task, leveraging Tkinter's GUI features to enhance the user experience in image management applications.
What is Tkinter?
Tkinter is a standard GUI (Graphical User Interface) toolkit for Python, providing a set of modules and libraries to create interactive and visually appealing desktop applications. Tkinter is based on the Tk GUI toolkit, and it comes bundled with most Python installations, making it readily available for developers. With Tkinter, developers can design windows, dialogs, buttons, and other GUI elements, facilitating the development of user-friendly applications with ease
Saving An Uploaded Image To A Local Directory Using Tkinter
Below, is the step-by-step guide to Saving An Uploaded Image To A Local Directory Using Tkinter in Python.
Create a Virtual Environment
First, create the virtual environment using the below commands
python -m venv env
.\env\Scripts\activate.ps1
Install Nessaccary Library
First, it is necessary to install the Pillow library, which enables the upload and display of images in Tkinter. Use the following command to install the required library.
pip install pillow
Code Explanation
Step 1: Importing Libraries
In first necessary libraries are imported. tkinter
provides GUI functionality, filedialog
and messagebox
modules handle file dialogs and message boxes, respectively. PIL
(Pillow) is used for image processing, and shutil
and os
assist in managing files and directories.
Python3
import tkinter as tk
from tkinter import filedialog, messagebox
from PIL import Image, ImageTk
import shutil
import os
Step 2: Defining the Upload Function
beloa code defines the upload_image
function, utilizing filedialog
to prompt the user to select an image file. It then opens and resizes the image using Pillow, updates the Tkinter label to display the image, and calls the save_image
function to store the image. A success message is displayed using messagebox
.
Python3
def upload_image():
file_path = filedialog.askopenfilename()
if file_path:
image = Image.open(file_path)
image.thumbnail((300, 300)) # Resize image if necessary
photo = ImageTk.PhotoImage(image)
image_label.config(image=photo)
image_label.image = photo # Keep a reference to avoid garbage collection
save_image(file_path)
messagebox.showinfo("Success", "Image uploaded successfully!")
Step 3: Image Saving Function
below code part defines save_image
, responsible for creating a directory (saved_images
) if it doesn't exist, extracting the filename from the provided path, and copying the image to the specified directory. A message is printed indicating the successful saving of the image.
Python3
def save_image(file_path):
save_dir = "saved_images"
if not os.path.exists(save_dir):
os.makedirs(save_dir)
filename = os.path.basename(file_path)
shutil.copy(file_path, os.path.join(save_dir, filename))
print("Image saved to:", os.path.join(save_dir, filename))
Step 4: Creating the Tkinter Window
In the pbelow code art, the Tkinter window is created with the title "Image Uploader" and a size of 500x500 pixels.
Python3
root = tk.Tk()
root.title("Image Uploader")
root.geometry("500x500")
Step 5: Create and Pack Widgets, Running the Application
The last part involves creating Tkinter widgets - a button (upload_button
) and a label (image_label
). The button triggers the upload_image
function when clicked, and both widgets are packed into the window. The mainloop()
method is called to run the Tkinter application, allowing user interaction with the image uploader interface.
Python3
upload_button = tk.Button(root, text="Upload Image", command=upload_image)
upload_button.pack(pady=10)
image_label = tk.Label(root)
image_label.pack()
root.mainloop()
Complete Code
Python3
import tkinter as tk
from tkinter import filedialog, messagebox
from PIL import Image, ImageTk
import shutil
import os
# Define the function to upload and save the image
def upload_image():
file_path = filedialog.askopenfilename()
if file_path:
image = Image.open(file_path)
image.thumbnail((300, 300)) # Resize image if necessary
photo = ImageTk.PhotoImage(image)
image_label.config(image=photo)
image_label.image = photo # Keep a reference to avoid garbage collection
save_image(file_path)
messagebox.showinfo("Success", "Image uploaded successfully!")
def save_image(file_path):
save_dir = "saved_images"
if not os.path.exists(save_dir):
os.makedirs(save_dir)
filename = os.path.basename(file_path)
shutil.copy(file_path, os.path.join(save_dir, filename))
print("Image saved to:", os.path.join(save_dir, filename))
# Create the main window
root = tk.Tk()
root.title("Image Uploader")
# Set window size
root.geometry("500x500")
# Create and pack widgets
upload_button = tk.Button(root, text="Upload Image", command=upload_image)
upload_button.pack(pady=10)
image_label = tk.Label(root)
image_label.pack()
# Run the application
root.mainloop()
Run the server
run the server using below command
python script_name.py
Output
Similar Reads
GST Rate Finder GUI using Python-Tkinter Prerequisites : Introduction to tkinter | Program to calculate GSTPython offers multiple options for developing a GUI (Graphical User Interface). Out of all the GUI methods, Tkinter is the most commonly used method. In this article, we will learn how to create GST Rate Finder GUI application using T
3 min read
File Explorer in Python using Tkinter Prerequisites: Introduction to Tkinter Python offers various modules to create graphics programs. Out of these Tkinter provides the fastest and easiest way to create GUI applications. The following steps are involved in creating a tkinter application: Importing the Tkinter module. Creation of the
2 min read
Image Viewer App in Python using Tkinter Prerequisites: Python GUI â tkinter, Python: Pillow Have you ever wondered to make a Image viewer with the help of Python? Here is a solution to making the Image viewer with the help of Python. We can do this with the help of Tkinter and pillow. We will discuss the module needed and code below. Mod
5 min read
How to use HTML in Tkinter - Python? Prerequisite: Tkinter Python offers multiple options for developing GUI (Graphical User Interface). Out of all the GUI methods, Tkinter is the most commonly used method. It is a standard Python interface to the Tk GUI toolkit shipped with Python. Python with Tkinter is the fastest and easiest way to
2 min read
Standard GUI Unit Converter using Tkinter in Python Prerequisites: Introduction to tkinter, Introduction to webbrowser In this article, we will learn how to create a standard converter using tkinter. Now we are going to create an introduction window that displays loading bar, welcome text, and user's social media profile links so that when he/she sha
12 min read
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 instal
3 min read
Scientific GUI Calculator using Tkinter in Python Prerequisite: Python GUI â tkinter In this article, we are going to create GUI Scientific Calculator using Python. As you can see, calculating large numbers nowadays is difficult or time-consuming. We've created a simple Scientific Calculator GUI using Python that allows you to perform simple and co
13 min read
How to save file with file name from user using Python? Prerequisites: File Handling in PythonReading and Writing to text files in Python Saving a file with the user's custom name can be achieved using python file handling concepts. Python provides inbuilt functions for working with files. The file can be saved with the user preferred name by creating a
5 min read
Create a Yes/No Message Box in Python using tkinter Python offers a number Graphical User Interface(GUI) framework but Tk interface or tkinter is the most widely used framework. It is cross-platform which allows the same code to be run irrespective of the OS platform (Windows, Linux or macOS). Tkinter is lightweight, faster and simple to work with. T
4 min read
How To Place An Image Into A Frame In Tkinter? In this article, we will walk through the process of placing an image into a frame in Tkinter. We will cover everything from setting up your environment to loading and displaying images using the PIL (Python Imaging Library) module, specifically Pillow. By the end of this tutorial, you will have a s
5 min read