python-3.x - 从 sqlite 检索图像并添加到列表框 tkinter python
问题描述
我试图从我的数据库中获取一个 blob 图像并将其插入到列表框中,但我不能。有什么办法吗?
我的整个代码:
from tkinter import *
from tkinter import messagebox, Tk, Label, filedialog, font
from blobdb import Database
from PIL import ImageTk, Image
from resizeimage import resizeimage
import re
import sqlite3
def fetch_contact ():
listBox.delete (0, END)
sqliteConnection = sqlite3.connect('store.db')
cursor = sqliteConnection.cursor()
print("Connected to SQLite")
sqlite_select_query = """SELECT * from contacts"""
cursor.execute(sqlite_select_query)
records = cursor.fetchall()
for row in records:
listBox.insert (END, (row[1], row[2]))
def convertToBinaryData(filename):
# Convert digital data to binary format
with open(filename, 'rb') as file:
blobData = file.read()
return blobData
def insertBLOB(id, name, last_name, photo, phone_num, email, home_address):
print(id, name, last_name, photo, phone_num, email)
try:
sqliteConnection = sqlite3.connect('store.db')
cursor = sqliteConnection.cursor()
print("Connected to SQLite")
sqlite_insert_blob_query = """ INSERT INTO contacts (id, name, last_name, photo, phone_num, email, home_address) VALUES (?, ?, ?, ?, ?, ?, ?)"""
empPhoto = convertToBinaryData(photo)
# Convert data into tuple format
data_tuple = (id, name, last_name, empPhoto,
phone_num, email, home_address)
cursor.execute(sqlite_insert_blob_query, data_tuple)
sqliteConnection.commit()
listBox.delete (0, END)
fetch_contact()
print("Image and file inserted successfully as a BLOB into a table")
cursor.close()
except sqlite3.Error as error:
print("Failed to insert blob data into sqlite table", error)
finally:
if (sqliteConnection):
sqliteConnection.close()
print("the sqlite connection is closed")
def clear_contacts():
global photo, image_entry, name_id, image, show_image, image_label
photo = 'no_image.jpg'
image_entry = Entry(app, textvariable=photo)
name_id = ''
name_entry.delete(0, END)
lastname_entry.delete(0, END)
phone_entry.delete(0, END)
email_entry.delete(0, END)
address_entry.delete(0, END)
def send_data():
global photo, image_entry
regex_email = '^[a-z0-9]+[\._]?[a-z0-9]+[@]\w+[.]\w{2,3}$'
regex_names = '^[a-zA-Zا-ی]'
regex_phone = '^[0-9]'
def check_email(email):
if (re.search(regex_email, email)):
return True
else:
return False
def check_names(name):
if (re.search(regex_names, name)):
return True
else:
return False
def check_phone(phone):
if (re.search(regex_phone, phone)):
return True
else:
return False
if name_value.get() == '' or lastname_value.get() == '' or phone_value.get() == '' or email_value.get() == '' or address_value.get() == '':
messagebox.showerror("Required Fields", "Please include all fields")
return
if not check_names(name_value.get()):
messagebox.showerror(
"Error", "Please Write Your Firstname Corectly(Just a-z A-Z)")
return
if not check_names(lastname_value.get()):
messagebox.showerror(
"Error", "Please Write Your Lastname Corectly(Just a-z A-Z)")
return
if not check_phone(phone_value.get()):
messagebox.showerror(
"Error", "Please Write Your Phone Number Corectly(Just 0-9)")
return
if not check_email(email_value.get()):
messagebox.showerror("Error", "This Email Is Not A Valid Email")
return
if photo == '':
photo = 'no_image.jpg'
image_entry = Entry(app, textvariable=photo)
name_id = id(name_value.get())
insertBLOB(name_id, name_value.get(), lastname_value.get(), photo, phone_value.get(), email_value.get(), address_value.get())
def open_image ():
global photo, image_entry, image, show_image, image_label
photo = filedialog.askopenfilename (initialdir="/", title='Select A File', filetypes = (('png files', '*.png'), ('jpg files', '*.jpg')))
image_entry = Entry (app, textvariable=photo)
image = photo[:]
show_image = ImageTk.PhotoImage (Image.open (image).resize ((80, 80), Image.ANTIALIAS))
image_label = Label (app, text='', image=show_image)
image_label.grid (row = 0, column = 1)
app = Tk()
app.title('Contact List')
app.geometry('400x600')
app.configure(background='RoyalBlue4')
icon_image = ImageTk.PhotoImage(Image.open('Alora_icon.ico').resize((20, 20), Image.ANTIALIAS))
app.iconbitmap(icon_image)
regex_email = '^[a-z0-9]+[\._]?[a-z0-9]+[@]\w+[.]\w{2,3}$'
regex_names = '^[a-zA-Zا-ی]'
regex_phone = '^[0-9]'
# list box
sf= font.Font (family='Helvetica', size=36, weight='bold')
listBox = Listbox (app, height = 6, width = 15, font = sf)
listBox.place (x = 50, y = 280)
# Scrollbar
scrollbar = Scrollbar (app)
scrollbar.place (x = 378, y = 280)
# set scrollbar to list
listBox.configure (yscrollcommand = scrollbar.set)
scrollbar.configure (command = listBox.yview)
fetch_contact()
# name input
name_value = StringVar ()
name = Label (app, text="FIRST NAME")
name.grid (row=1, column=0, sticky=W)
name_entry = Entry (app, textvariable=name_value)
name_entry.grid (row=1, column=1, sticky=W, padx = 4, pady = 2)
# last name input
lastname_value = StringVar ()
lastname = Label (app, text="LAST NAME")
lastname.grid (row=2, column=0, sticky=W)
lastname_entry = Entry (app, textvariable=lastname_value)
lastname_entry.grid (row=2, column=1, sticky=W, padx = 4, pady = 2)
# Image
photo = 'no_image.jpg'
image_entry = Entry (app, textvariable=photo)
image = photo[:]
show_image = ImageTk.PhotoImage (Image.open (image).resize ((80, 80), Image.ANTIALIAS))
image_label = Label (app, text='', image=show_image)
image_label.grid (row = 0, column = 1, padx = 4, pady = 2)
# phone input
phone_value = StringVar ()
phone = Label (app, text="PHONE")
phone.grid (row=3, column=0, sticky=W)
phone_entry = Entry (app, textvariable=phone_value)
phone_entry.grid (row=3, column=1, sticky=W, padx = 4, pady = 2)
# Email input
email_value = StringVar ()
email = Label (app, text="EMAIL")
email.grid (row=4, column=0, sticky=W)
email_entry = Entry (app, textvariable=email_value)
email_entry.grid (row=4, column=1, sticky=W, padx = 4, pady = 2)
# home address input
address_value = StringVar ()
address = Label (app, text="HOME ADDRESS")
address.grid (row=5, column=0, sticky=W)
address_entry = Entry (app, textvariable=address_value)
address_entry.grid (row=5, column=1, sticky=W, padx = 4, pady = 2)
name_id = id (name_value.get())
# menubar = Menu (app)
# filemenu = Menu(menubar, tearoff=0)
# filemenu.add_command(label="Add Contact", command= print())
# menubar.add_cascade(label="File", menu=filemenu)
# app.config(menu=menubar)
add_btn = Button (app, text='ADD CONTACTS', width=12, command=lambda: send_data ())
add_btn.grid (row=7, column=1)
add_photo_btn = Button (app, text='ADD PHOTO', width=12, command=lambda: open_image ())
add_photo_btn.grid (row=0, column=0)
# Start program
app.mainloop ()
解决方案
推荐阅读
- python - 使用 Python 按名称复制特定子目录
- html - 如何在悬停时切换 div 的可见性?
- flutter - 当 `maxLines` 为空时,如何使 `TextFormField` `prefixIcon` 保持在顶部对齐?
- java - 与 Jackson 一起使用 Jayway JsonPath
- c# - 列表
Add 方法在 Button.Click 事件中不起作用,但在 Form.Load 中起作用 - java - Spring:迁移到 OpenJDK-10 不工作,mvn install 工作
- knife - 如何从我的笔记本电脑轻松连接到 AWS 机器?
- javascript - Javascript 片段在 Safari 11 和 12 中不起作用
- angular - Angular/Firebase - Guard 在 Firebase 初始化完成之前运行
- jenkins - 如何使用“Jenkins 配置即代码”Jenkins 插件 (JCASC) 配置 Fortify 插件?