Adding Image to MySQL Blob column in Tkinter


Adding uploaded image with data to MySQL table in Tkinter GUI
We will ask user to enter Name using Entry , select one Id from OptionMenu and then upload any JPG or PNG image. These data we will store in MySQL table on click of a Button.

We have already discussed about the structure of the student_profile table and how to display the records with uploaded photo here.


Tkinter GUI application to add, display update and delete Blob column data with image of MySQL table
We will first display the Tkinter GUI with all input elements.
import tkinter as tk
from tkinter import filedialog
from tkinter.filedialog import askopenfile
from PIL import Image, ImageTk
from sqlalchemy import create_engine

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',font=my_font1)  
l1.grid(row=1,column=1,columnspan=5)

l2 = tk.Label(my_w,  text='Name', width=10 )  # added one Label 
l2.grid(row=2,column=1)

e1 = tk.Entry(my_w,width=10,bg='yellow') # added one Entry box
e1.grid(row=2,column=2)

my_list = [1,2,3,4] # options to appear for selection
options = tk.StringVar(my_w)

options.set(my_list[1]) # default value selected
om1 =tk.OptionMenu(my_w, options, *my_list)

om1.grid(row=2,column=3) # displaying option Menu
b1 = tk.Button(my_w, text='Upload File', 
   command = lambda:upload_file())
b1.grid(row=2,column=4) 

my_font=('times', 12, 'bold')
b2 = tk.Button(my_w, text='Add data', font=my_font,
   command = lambda:add_data())
b2.grid(row=2,column=5,padx=20) 
global filename # Access this from both functions
##### function to upload_file() ###
##### function to add_data() ####
my_w.mainloop()  # Keep the window open
Above code shows the window with inputs and buttons. The two buttons b1 and b2 triggers two different functions.
One is upload_file() to show the file browser and allow uploading of file. After uploading the same image is displayed on the window showing a sample to the user about the image going to be stored in the database table.
Upload and display image in Tkinter GUI
Here is the code to upload and display the image within the function.
def upload_file(): # Image upload and display
    global filename,img
    f_types =[('Png files','*.png'),('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=4,column=1,columnspan=2)#display uploaded photo
The second function add_data() reads the user entered data in Entry element ( name ) user selection of OptionMenu ( id ) and the uploaded image. After connecting to MySQL database, it add the data to table. As a confirmation of data insertion to MySQL table , we use the function rowcount to get number of records added to the table. This number is displayed in the console. Same can be displayed in the window also.
def add_data(): # Add data to MySQL table 
    global img , filename 
    fob=open(filename,'rb') # filename from upload_file()
    fob=fob.read()
    data=(options.get(),e1.get(),fob) # tuple with data 
    my_conn = create_engine("mysql+mysqldb://root:test@localhost/my_tutorial")
    id=my_conn.execute("INSERT INTO  student_profile(id,student,profile_photo) \
                  VALUES (%s,%s,%s)",data)
    print("Row Added  = ",id.rowcount) # displayed in console 
    my_w.destroy() # close window after adding data
Here to keep the code simple and small, the validation part is not included but same can be added. Here is a list of validation you may consider adding to the script.
  1. The button to add data can be kept as disabled unless some minimum length of text is entered as name and the image file is uploaded. Read how to disable / enable a button here
  2. While displaying the image the size can be reduced to match the window size. Here all sample images shown are of small sizes so they fit to the window. Check how to reduce the size of the image using PIL
  3. Check if the ID selected by the user is already available in the table.
Full code is here
import tkinter as tk
from tkinter import filedialog
from tkinter.filedialog import askopenfile
from PIL import Image, ImageTk
from sqlalchemy import create_engine
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',font=my_font1)  
l1.grid(row=1,column=1,columnspan=5)

l2 = tk.Label(my_w,  text='Name', width=10 )  # added one Label 
l2.grid(row=2,column=1)

e1 = tk.Entry(my_w,width=10,bg='yellow') # added one Entry box
e1.grid(row=2,column=2)

my_list = [1,2,3,4] # options to appear for selection
options = tk.StringVar(my_w)

options.set(my_list[1]) # default value selected
om1 =tk.OptionMenu(my_w, options, *my_list)

om1.grid(row=2,column=3) # displaying option Menu
b2 = tk.Button(my_w, text='Upload File', 
   command = lambda:upload_file())
b2.grid(row=2,column=4) 
my_font=('times', 12, 'bold')
b3 = tk.Button(my_w, text='Add data', font=my_font,
   command = lambda:add_data())
b3.grid(row=2,column=5,padx=20) 

global filename # Access this from both functions
def upload_file(): # Image upload and display
    global filename,img
    f_types =[('Png files','*.png'),('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=4,column=1,columnspan=2)#display uploaded photo

def add_data(): # Add data to MySQL table 
    global img , filename 
    fob=open(filename,'rb') # filename from upload_file()
    fob=fob.read()
    data=(options.get(),e1.get(),fob) # tuple with data 
    my_conn = create_engine("mysql+mysqldb://root:test@localhost/my_tutorial")
    id=my_conn.execute("INSERT INTO  student_profile(id,student,profile_photo) \
                 VALUES (%s,%s,%s)",data)
    print("Row Added  = ",id.rowcount) # displayed in console 
    my_w.destroy() # close window after adding data

my_w.mainloop()  # Keep the window open

Adding data with Photo to student table using Tkinter GUI
Tkinter window to display MySQL Blob Data type image( Single record)
Tkinter window to display MySQL Blob Data type image( All records)
Tkinter update Blob Data type with user uploaded image
Tkinter delete record with Blob Data type
Tkinter MySQL Record display MySQL Update MySQL Delete
Changes required for using SQLite database in place of MySQL
Subscribe to our YouTube Channel here


Subscribe

* indicates required
Subscribe to plus2net

    plus2net.com



    25-02-2023

    I am not able to save record in database Error insert into ???

    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-2024 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer