Tkinter使用filedialog上传图片后点击存储按钮无法存入SQLite数据库
问题根因
- 作用域冲突:
uploadImg函数内给var_photo赋值时未声明全局变量,直接生成了局部Label对象,覆盖了全局定义的StringVar类型var_photo,插入数据时调用var_photo.get()只能拿到空值 - 数据格式不匹配:SQLite的
BLOB字段要求传入二进制字节流,原代码完全没有做图片到二进制的转换逻辑,不可能正确入库 - 冗余代码:重复导入了
ttk模块,且定义的var_photo类型不符合存储需求
修正后可运行代码
from tkinter import * from tkinter import ttk, messagebox, filedialog from PIL import Image, ImageTk import sqlite3 from io import BytesIO 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 )") con.close() # ==========Variables================ var_name = StringVar() # 全局变量存储图片二进制数据 photo_data = None # ==========Method to Upload Image ================ def uploadImg(): global photo_data filename = filedialog.askopenfilename(initialdir="/", title="Select an Image", filetype=(("jpeg files", "*.jpg"), ("PNG files", "*.png"))) if not filename: return image = Image.open(filename) # Read the Image resize_image = image.resize((200, 150)) # Resize the image using resize() method show_img = ImageTk.PhotoImage(resize_image) # create label and to add the resize image # 清空之前显示的图片 for widget in img_LabelFrame.winfo_children(): widget.destroy() img_label = Label(img_LabelFrame, image=show_img) img_label.image = show_img img_label.pack() # 转换图片为二进制字节流 buf = BytesIO() format = 'JPEG' if filename.lower().endswith('.jpg') else 'PNG' resize_image.save(buf, format=format) photo_data = buf.getvalue() # ==========Method to add The Name and Image to Database ================ def add(): global photo_data con = sqlite3.connect(database="std.db") cur = con.cursor() try: if var_name.get() == "": messagebox.showerror("Error", "Student Name is Required") return if photo_data is None: messagebox.showerror("Error", "Please upload student photo first") return cur.execute("select * from std where name =? ", (var_name.get(),)) row = cur.fetchone() if row != None: messagebox.showerror("Error", "Student name is already exists") return cur.execute("insert into std (name,photo) values (?,?)", ( var_name.get(), photo_data )) con.commit() messagebox.showinfo("Success", "Student Add Successfully") # 保存成功后重置表单 var_name.set("") photo_data = None for widget in img_LabelFrame.winfo_children(): widget.destroy() except Exception as ex: messagebox.showerror("Error", f"Error due to {str(ex)}") finally: con.close() # ==========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()
内容的提问来源于stack exchange,提问作者Murad Amer
相关产品推荐
相关产品推荐

