【问题标题】:How to display a BLOB image stored in my SQLite database?如何显示存储在我的 SQLite 数据库中的 BLOB 图像?
【发布时间】:2021-11-16 22:19:10
【问题描述】:

我有一个带有条目和 4 个按钮的 CRUD 表单,用于从我的数据库中删除、更新、创建、获取值,我想实现另一个按钮来打开一个绑定到我的 的图像>id entry 也可以与我的删除、更新、创建、获取按钮一起使用,我一直在尝试使用 BLOB,并且可以将图像保存在我的数据库中斑点。实际上我知道我需要为我的条目创建 textvariables 像 'idvar = StringVar() , namevar = Stringvar()..., 等等',所以我不知道该怎么做一个图像标签,以便使用我的 CRUD 按钮删除、更新、创建、获取

这是我目前得到的代码,它可以很好地将图像保存到我的照片列中:

from tkinter import *
import sqlite3

top = Tk()
top.configure(width='444', heigh='400')

conn = sqlite3.connect('test.db')
c = conn.cursor()

def enterdata():
    id = 'hello'
    photo = convert_pic()
    c.execute('INSERT INTO test (id, photo) VALUES (?, ?)', (id, photo)) #Here my id has integer value and my photo has BLOB value in my database 
    conn.commit()

def convert_pic():
    filename = 'images/image6.jpg'
    with open(filename, 'rb') as file:
        photo = file.read()
    return photo


btn = Button(top, text='save photo', command=enterdata)
btn.place(x='100', y='111')


mainloop()

【问题讨论】:

  • 注意:command=enterdata() 应该是command=enterdata
  • @CoolCloud 我已经编辑过了。
  • 图片是否正确保存在数据库中?
  • @CoolCloud 是的,当我按下按钮 btn = Button(top, text='save photo', command=enterdata 时,图像 'images/image6.jpg' 已正确保存在我的数据库中

标签: python python-3.x tkinter blob tkinter-entry


【解决方案1】:

现在您有了 BLOB,您可以使用 io.BytesIO。我将创建一个示例来演示,例如:

from PIL import Image, ImageTk
from io import BytesIO

def show(data):
    img_byte = BytesIO(data)
    img = ImageTk.PhotoImage(Image.open(img_byte))
    Label(root,image=img).pack()
    root.image = img # Keep a reference

所以现在您可以查询数据库并获取值:

def fetch():
    c = con.cursor()
    id = 1 # Any id
    c.execute('SELECT photo FROM test where id=?',(id,))
    data = c.fetchall()[0][0] # Get the blob data
    show(data) # Call the function with the passes data

这将在输入 id 的根窗口的标签中显示图像。

【讨论】:

  • @CooCloud 它显示了这个错误IndexError: tuple index out of range,我拿了[0][1],因为我的照片在第二列
  • @Paul 你试过[0][0]吗,因为我们只选择一列。
  • 我试过[0][0],但是一旦按下按钮来调用该功能,它似乎照片被充电并且它扩大了窗口,但我看不到照片本身
  • @Paul 对不起,我的错,将root.image = img 添加到show() 的末尾。
  • 太棒了,它工作正常,虽然我对我的 CRUD 表单有点困惑,你能给我一些建议如何用照片实现它吗?我应该再发一个问题还是直接写在这里?
猜你喜欢
  • 2017-08-19
  • 2012-10-24
  • 1970-01-01
  • 1970-01-01
  • 2013-01-16
  • 1970-01-01
  • 1970-01-01
  • 2021-06-05
相关资源
最近更新 更多