Simply, I upload image by tkinter.filedialog
functions and wanted the image to be stored to the database simultaneous with the name I provide by clicking another the button, the name stored well but not the image.
Here is the code.
from tkinter import *
from tkinter import ttk
from PIL import Image,ImageTk
from tkinter import ttk,messagebox
from tkinter import filedialog
import sqlite3
root=Tk()
root.geometry("600x400")
#==========Database================
con = sqlite3.connect(database="std.db")
cur = con.cursor()
cur.execute("CREATE TABLE IF NOT EXISTS std (name TEXT, photo BLOB )")
#==========Variblels================
var_name = StringVar()
var_photo = StringVar()
#==========Method to Upload Image ================
def uploadImg():
filename = filedialog.askopenfilename(initialdir = "/", title = "Select an Image", filetype = (("jpeg files","*.jpg"),("PNG files","*.png")))
image = Image.open(filename) # Read the Image
resize_image = image.resize((200, 150)) # Reszie the image using resize() method
show_img = ImageTk.PhotoImage(resize_image) # create label and to add the resize image
var_photo = Label(img_LabelFrame,image=show_img)
var_photo.image = show_img
var_photo.pack()
#==========Method to add The Name and Image to Database ================
def add():
con=sqlite3.connect(database="std.db")
cur=con.cursor()
try:
if var_name.get()=="":
messagebox.showerror("Error","Student Name is Required")
else:
cur.execute("select * from std where name =? ",( var_name.get(),) )
row=cur.fetchone()
if row!=None:
messagebox.showerror("Error","Student name is already exists")
else:
cur.execute("insert into std (name,photo) values (?,?)",(
var_name.get(),
var_photo.get()
))
con.commit()
messagebox.showinfo("Success", "Student Add Successfully")
except Exception as ex:messagebox.showerror("Error",f"Error duo to {str(ex)}")
#==========Entry Fileds ================
bl_Name=Label(root,text="Student Name:", font= ("Arial",15,)).place(x=10,y=40 )
En_Name= Entry( textvariable=var_name , font= ("Arial",15,), bg="lightyellow" ).place(x=150, y=40, width=250)
lbl_Std_photo = Label(root, text="Student Photo: ", font= ("Arial",15,)).place(x=10,y=90 )
img_LabelFrame = ttk.LabelFrame(root, text="")
img_LabelFrame.place(x=150,y=90, width=200,height=150)
btn_upload_img = Button(text="Upload Image", bg="green", command= uploadImg).place(x=200, y=280, width= 150 , height=40)
btn_save = Button( text="Save", bg="green", command=add).place(x=200, y=330, width= 150 , height=40)
mainloop()